在字符串中检测CJK字符 (C#)

7
我正在使用iTextSharp生成一系列PDF,使用Open Sans作为默认字体。偶尔,我需要将名称插入PDF内容中。然而,我的问题是,我需要插入的一些名称包含CJK字符(存储在SQL Server的nvarchar列中),据我所知,Open Sans目前不支持CJK字符。我需要继续使用Open Sans作为我的默认字体,因此理想情况下,我希望尝试检测从数据库中获取的字符串中的CJK字符,并在打印这些字符时切换到CJK字体。
正则表达式是否是最佳选择?不幸的是,我无法找到任何可以帮助解决此问题的正则表达式模式。
感谢您提前的帮助!
3个回答

11

如果有人偶然遇到这个问题,我发现可以使用在正则表达式中列出的Unicode块(http://msdn.microsoft.com/en-us/library/20bw873z.aspx#SupportedNamedBlocks)来找到另一个解决方案。

var Name = "Joe Bloggs";
var Regex = new Regex(@"\p{IsCJKUnifiedIdeographs}");

if(Regex.IsMatch(Name))
{
    //switch to CJK font
}
else
{
    //keep calm and carry on
}

编辑:

您可能需要匹配更多内容,不仅仅是统一表意文字,请尝试使用以下正则表达式:

string r = 
@"\p{IsHangulJamo}|"+
@"\p{IsCJKRadicalsSupplement}|"+
@"\p{IsCJKSymbolsandPunctuation}|"+
@"\p{IsEnclosedCJKLettersandMonths}|"+
@"\p{IsCJKCompatibility}|"+
@"\p{IsCJKUnifiedIdeographsExtensionA}|"+
@"\p{IsCJKUnifiedIdeographs}|"+
@"\p{IsHangulSyllables}|"+
@"\p{IsCJKCompatibilityForms}"; 

我尝试过的所有韩文都可以使用该程序。


是的,我认为那应该能全部捕获! - user1961026

2

使用iTextSharp.text.pdf.FontSelector;

iTextSharp.text.pdf.FontSelector selector = new iTextSharp.text.pdf.FontSelector();

// add 2 type of font to FontSelector
selector.AddFont(openSansfont);
selector.AddFont(chinesefont);


iTextSharp.text.Phrase phrase = selector.Process(yourTxt);

FontSelector将为您使用正确的字体!

源文件FontSelector.cs中的详细说明。

选择适当的字体,其中包含呈现文本所需的字形。按顺序检查字体,直到找到字符为止。

我忘记了它搜索的顺序!!请自行体验! 编辑:顺序是从第一个addFont到最后一个addFont。

http://itextpdf.com/examples/iia.php?id=214


一定会尝试的。谢谢 Wong! - user1961026

2

我已经编辑了Dave的回答以使其可行,但显然只有我能看到,直到它被同行评审。因此,我将把解决方案发布为我的答案。基本上,Dave只需要将他的正则表达式扩展到这个程度:

string regex = 
@"\p{IsHangulJamo}|"+
@"\p{IsCJKRadicalsSupplement}|"+
@"\p{IsCJKSymbolsandPunctuation}|"+
@"\p{IsEnclosedCJKLettersandMonths}|"+
@"\p{IsCJKCompatibility}|"+
@"\p{IsCJKUnifiedIdeographsExtensionA}|"+
@"\p{IsCJKUnifiedIdeographs}|"+
@"\p{IsHangulSyllables}|"+
@"\p{IsCJKCompatibilityForms}"; 

这将会在以下方式中检测韩文字符:
string subject = "도형이";

Match match = Regex.Match(subject, regex);

if(match.Success)
{
    //change to Korean font
}
else
{
    //keep calm and carry on
{

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接