Regex对Unicode地支持和Unicode地BOM

我们知道正则式可以用/uxxxx来表示Unicode编码,比如用[/u4e00-/u9fa5] 来表示双字节字符。

博客园有位朋友留言问我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"));
            }
返回的结果是2D4E,
然后我写正则式来匹配它

            string s = "中";
            Regex reg = new Regex(@"/u2d4e",RegexOptions.Compiled);
            WL(reg.IsMatch(s));结果却返回False!!

想了半天,记起Unicode的字节存放有前高后低(前一字节放高位后一字节放低位)和前低后高两种,于是把字节前后对换

            string s = "中";
            Regex reg = new Regex(@"/u4e2d",RegexOptions.Compiled);
            WL(reg.IsMatch(s));此时,返回的是希望看到的True。

后来通过查看
            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顺序。

看到得去补补编码知识了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值