博客园有位朋友留言问我Regex怎么支持Unicode,于是我想取出一个汉字的Unicode编码,写到Regex 的Pattern中,来说明这个问题。
string s = "中";
byte[] bs = Encoding.Unicode.GetBytes(s);
for(int i = 0 ; i < bs.Length ;i++)
{
Console.Write(bs[i].ToString("X"));
}
byte[] bs = Encoding.Unicode.GetBytes(s);
for(int i = 0 ; i < bs.Length ;i++)
{
Console.Write(bs[i].ToString("X"));
}
返回的结果是2D4E,
然后我写正则式来匹配它
string s = "中";
Regex reg = new Regex(@"\u2d4e",RegexOptions.Compiled);
WL(reg.IsMatch(s));
结果却返回False!!Regex reg = new Regex(@"\u2d4e",RegexOptions.Compiled);
WL(reg.IsMatch(s));
想了半天,记起Unicode的字节存放有前高后低(前一字节放高位后一字节放低位)和前低后高两种,于是把字节前后对换
string s = "中";
Regex reg = new Regex(@"\u4e2d",RegexOptions.Compiled);
WL(reg.IsMatch(s));
此时,返回的是希望看到的True。Regex reg = new Regex(@"\u4e2d",RegexOptions.Compiled);
WL(reg.IsMatch(s));
后来通过查看
Encoding unicode = Encoding.Unicode;
// Get the byte order mark (BOM) of the Unicode encoder.
byte[] preamble = unicode.GetPreamble();
if(preamble[0] == 0xFE && preamble[1] == 0xFF)
{
Console.WriteLine("The Unicode encoder is encoding in big-endian order.");
}
else if(preamble[0] == 0xFF && preamble[1] == 0xFE)
{
Console.WriteLine("The Unicode encoder is encoding in little-endian order.");
}
得知.NET下的Unicode编码默认采用little-endian顺序。// Get the byte order mark (BOM) of the Unicode encoder.
byte[] preamble = unicode.GetPreamble();
if(preamble[0] == 0xFE && preamble[1] == 0xFF)
{
Console.WriteLine("The Unicode encoder is encoding in big-endian order.");
}
else if(preamble[0] == 0xFF && preamble[1] == 0xFE)
{
Console.WriteLine("The Unicode encoder is encoding in little-endian order.");
}
看到得去补补编码知识了。