2013-11-27 59 views
2

我必須從以下regEx驗證電話號碼。驗證來自regEx的用戶輸入

//**regExpPattern** : "+?[0-9]{0,3}(|-)?[0-9]{4}(|-)?[0-9]{3}(|-)?[0-9]{3}" 
-(BOOL) textFieldValidation:(NSString *)checkString withRegEx:(NSString*)regExpPattern 
{ 
     NSString *stringToValidate = [[NSString alloc]initWithString:checkString]; 
     NSString *pattern = [[NSString alloc]initWithString:regExpPattern] 
     NSLog(@"%@ %@",checkString,regExpPattern); 


     NSPredicate *myTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern]; 

      if ([myTest evaluateWithObject:stringToValidate]){ 
       return YES; 
      } 
      return FALSE; 
     } 

,我發現了以下異常:

'NSInvalidArgumentException' 「不能做正則表達式匹配,原因是:(無法打開模式U_REGEX_RULE_SYNTAX(字符串6789054321,模式+? ] [0-9] {0,3}(| - )?[0-9] {4}(| - )?[0-9] {3}(| - )?[0-9] {3} ,case 0,canon 0))'

+0

http://stackoverflow.com/questions/3349494/objective-c-regex-to-check-phone-number – Laxmi

+0

一個簡單的..如果這可以幫助:http://www.iossnippet.com/snippets /驗證/如何對驗證-A-電話號碼功能於目標c-IOS / – GenieWanted

回答

3

+是一個特殊字符;你需要轉義(\+?)或正常(例如\s+?爲前導空格)

0

使用該模式使用這樣

[email protected]"(([+]{1}|[0]{2}){0,1}+[1]{1}){0,1}+[ ]{0,1}+(?:[-(]{0,1}[0-9]{3}[-) ]{0,1}){0,1}+[ ]{0,1}+[0-9]{2,3}+[0-9- ]{4,8}"; 
0

我太滿足了這個問題。 '+'確實是一個元字符,你應該明白你爲什麼使用'+'。

如果你想匹配'+'像一個正常字符,然後你應該使用'\ +'。

如果您將'+'視爲特殊字符,則需要匹配另一個字符。然後您應該在'+'之前添加該字符,然後它不會崩潰。

PS:在iOS謂詞中,'like'和'matches'不符合相同的正則表達式匹配規則!