最近在除錯正規表示式時,發現判斷數字的正規表示式中的\d
對全形字元判斷的不準,有的能判斷有時候又判斷不出來。然後經過一番搜尋發現\d
判斷的不只是0-9
,而是一個 Unicode 字符集,
參考這裡的描述:
\d ✓ ✓ Match any character with the Unicode General Category of Nd (Number, Decimal Digit.)
例如下面的測試:
- (void)testDRegex
{
NSArray *numbers = @[@"a",@"A",@"1",@"123456",
@"㆒㆓㆔",@"⑴⑵⑶",
@"①②③④⑤",@"????",
@"᮰᮱᮲᮳᮴᮵᮶᮷᮸᮹",@"ⅠⅡⅢⅣⅤⅥ",
@"??????????",@"ⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹⅺⅻ",@"?????????",
@"??",@"???",
@"?"];
for (NSString *string in numbers) {
BOOL mobile1R = [ValidateUtil validateString:string withRegex:@"^\\d*$"];
NSLog(@"Test \\d method:, string: %@,result: %@",string,@(mobile1R));
}
}
複製程式碼
輸出結果為:
Test \d method:, string: 123456,result: 1
Test \d method:, string: ㆒㆓㆔,result: 0
Test \d method:, string: ⑴⑵⑶,result: 0
Test \d method:, string: ①②③④⑤,result: 0
Test \d method:, string: ????,result: 1
Test \d method:, string: ᮰᮱᮲᮳᮴᮵᮶᮷᮸᮹,result: 1
Test \d method:, string: ⅠⅡⅢⅣⅤⅥ,result: 0
Test \d method:, string: ??????????,result: 1
Test \d method:, string: ⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹⅺⅻ,result: 0
Test \d method:, string: ?????????,result: 0
Test \d method:, string: ??,result: 1
Test \d method:, string: ???,result: 1
Test \d method:, string: ?,result: 1
複製程式碼
可以明顯看到\d
判斷的不只是0-9
等數字。
點選檢視Unicode Characters in the 'Number, Decimal Digit' Category
最後結論:為了正確匹配0-9數字,還是隻寫[0-9]
吧,不能再寫\d
了
參考:
1、http://userguide.icu-project.org/strings/regexp
2、http://fresky.github.io/2013/06/04/d-0-9-difference-in-regex/
3、https://stackoverflow.com/questions/890686/should-i-use-d-or-0-9-to-match-digits-in-a-perl-regex
4、https://stackoverflow.com/questions/16621738/d-is-less-efficient-than-0-9?newsletter=1&nlcode=55866%7cc739