又發現了一個 .net 的 bug!最近在使用Regex的時候發現:在忽略大小寫時候,匹配值從 0xff 到 0xffff 之間的所有字元,Regex竟然也能匹配兩個 ASCII 字元:i(code: 0x69) 和 I(code: 0x49);但是仍然不能匹配其他的 ASCII 字母和數字。
比如以下的代碼就是用來測試用Regex匹配從 0xff 到 0xffff 的字元。而值範圍在 0 到 0xfe 的所有字元是不能被匹配的。
Regex regex = new Regex(@"[\u00FF-\uFFFF]+");// The characters, whoes value are smaller than 0xff, are not expected to be matched.for (int i = 0; i < 0xff; i++) { string s = new string(new char[] { (char)i }); Debug.Assert( !regex.IsMatch(s), string.Format("The character was not expected to be matched: 0x{0:X}!", i));}// However, the characters whoes value are greater than 0xfe are expected to be matched.for (int i = 0xff; i <= 0xffff; i++) { string s = new string(new char[] { (char)i }); Debug.Assert( regex.IsMatch(s), string.Format("The character was expected to be matched: 0x{0:X}!", i));}
這時的運行結果是正常的,沒有任何的斷言錯誤出現。
然而當使用忽略大小寫匹配模式時,結果就不一樣了。將上面代碼中的第一行改成:
Regex regex = new Regex(@"[\u00FF-\uFFFF]+", RegexOptions.IgnoreCase);
程式啟動並執行時候就會有兩處斷言錯誤。它們分別是字元值為 73 和 105,也就是小寫字母 i 和大寫字母 I。 這個 bug 非常奇怪,別的字元都很正常!而且用 javascript 指令碼在 IE (版本是6.0)裡面運行也同樣有這麼 bug 存在(比如下面這段代碼)。然而在 Firefox 中運行就是沒有問題的。還是 Firefox 好啊,呵呵!
var re = /[\u00FF-\uFFFF]+/;// var re = /[\u00FF-\uFFFF]+/i;for(var i=0; i<0xff; i++) { var s = String.fromCharCode( i ); if ( re.test(s) ){ alert( 'Should not be matched: ' + i + '!' ); }}for(var i=0xff; i<=0xffff; i++) { var s = String.fromCharCode( i ); if ( !re.test(s) ){ alert( 'Should be matched: ' + i + '!' ); }}