.NET Regex中的 bug

來源:互聯網
上載者:User

又發現了一個 .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 + '!' );  }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.