.NET开发 正则表达式中的 Bug

来源:互联网 发布:淘宝天猫国际图标图片 编辑:程序博客网 时间:2024/05/18 06:26
<script type="text/javascript"><!--google_ad_client = "pub-4490194096475053";/* 内容页,300x250,第一屏 */google_ad_slot = "3685991503";google_ad_width = 300;google_ad_height = 250;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
  1. 又发现了一个 .net 的 bug!最近在使用正则表达式的时候发现:在忽略大小写的时候,匹配值从 0xff 到 0xffff 之间的所有字符,正则表达式竟然也能匹配两个 ASCII 字符:i(code: 0x69) 和 I(code: 0x49);但是仍然不能匹配其他的 ASCII 字母和数字。 
  2. 比如以下的代码就是用来测试用正则表达式匹配从 0xff 到 0xffff 的字符。而值范围在 0 到 0xfe 的所有字符是不能被匹配的。 
  3. 以下为引用的内容:   
  4. 1234567891011121314151617Regex regex = new Regex(@"[/u00FF-/uFFFF]+"); 
  5.   // The characters, whoes value are smaller than 0xff, are not expected to be matched. 
  6.   for (int i = 0; i < 0xff; i++) { 
  7.   string s = new string(new char[] { (char)i }); 
  8.   Debug.Assert( 
  9.   !regex.IsMatch(s), 
  10.   string.Format("The character was not expected to be matched: 0x{0:X}!", i)); 
  11.   } 
  12.   // However, the characters whoes value are greater than 0xfe are expected to be matched. 
  13.   for (int i = 0xff; i <= 0xffff; i++) { 
  14.   string s = new string(new char[] { (char)i }); 
  15.   Debug.Assert( 
  16.   regex.IsMatch(s), 
  17.   string.Format("The character was expected to be matched: 0x{0:X}!", i)); 
  18.   } 
  19. 这时的运行结果是正常的,没有任何的断言错误出现。 
  20. 然而当使用忽略大小写的匹配模式时,结果就不一样了。将上面代码中的第一行改成: 
  21. 以下为引用的内容: 
  22. 1Regex regex = new Regex(@"[/u00FF-/uFFFF]+", RegexOptions.IgnoreCase); 
  23. 程序运行的时候就会有两处断言错误。它们分别是字符值为 73 和 105,也就是小写字母 i 和大写字母 I。 这个 bug 非常奇怪,别的字符都很正常!而且用 javascript 脚本在 IE (版本是6.0)里面运行也同样有这么 bug 存在(比如下面这段代码)。然而在 Firefox 中运行就是没有问题的。还是 Firefox 好。 
  24. 以下为引用的内容: 
  25.  1234567891011121314151617var re = /[/u00FF-/uFFFF]+/; 
  26.   // var re = /[/u00FF-/uFFFF]+/i; 
  27.   for(var i=0; i<0xff; i++) { 
  28.   var s = String.fromCharCode( i ); 
  29.   if ( re.test(s) ){ 
  30.   alert( 'Should not be matched: ' + i + '!' ); 
  31.   } 
  32.   } 
  33.   for(var i=0xff; i<=0xffff; i++) { 
  34.   var s = String.fromCharCode( i ); 
  35.   if ( !re.test(s) ){ 
  36.   alert( 'Should be matched: ' + i + '!' ); 
  37.   } 
  38.   } 
<script type="text/javascript"><!--google_ad_client = "pub-4490194096475053";/* 728x90, 创建于 08-12-8 */google_ad_slot = "0403648181";google_ad_width = 728;google_ad_height = 90;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击