為你解疑:VB.NET開發(fā)正則表達(dá)式bug原因
很多朋友都喜歡找語(yǔ)言編程的bug,感覺(jué)有成就感,在用VB.NET開發(fā)正則表達(dá)式時(shí)我發(fā)現(xiàn)了一個(gè)bug!最近在使用正則表達(dá)式的時(shí)候發(fā)現(xiàn):在忽略大小寫的時(shí)候,匹配值從 0xff 到 0xffff 之間的所有字符,正則表達(dá)式竟然也能匹配兩個(gè) ASCII 字符:i(code: 0x69) 和 I(code: 0x49);但是仍然不能匹配其他的 ASCII 字母和數(shù)字。
比如以下的代碼就是用來(lái)測(cè)試用VB.NET開發(fā)正則表達(dá)式匹配從 0xff 到 0xffff 的字符。而值范圍在 0 到 0xfe 的所有字符是不能被匹配的。
- 1234567891011121314151617Regex 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));
- }
這時(shí)的運(yùn)行結(jié)果是正常的,沒(méi)有任何的斷言錯(cuò)誤出現(xiàn)。然而當(dāng)使用忽略大小寫的匹配模式時(shí),結(jié)果就不一樣了。將上面代碼中的第一行改成:
- 1Regex regex = new Regex(@"[/u00FF-/uFFFF]+", RegexOptions.IgnoreCase);
程序運(yùn)行的時(shí)候就會(huì)有兩處斷言錯(cuò)誤。它們分別是字符值為 73 和 105,也就是小寫字母 i 和大寫字母 I。 這個(gè) bug 非常奇怪,別的字符都很正常!而且用 javascript 腳本在 IE (版本是6.0)里面運(yùn)行也同樣有這么 bug 存在(比如下面這段代碼)。然而在 Firefox 中運(yùn)行就是沒(méi)有問(wèn)題的。還是 Firefox 好啊,呵呵!
- 1234567891011121314151617var 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 + '!' );
- }
- }
以上就是關(guān)于VB.NET開發(fā)正則表達(dá)式找出一個(gè)bug的分析。
【編輯推薦】