2013-01-09 35 views
1

UITextBoxfield,我插入一些值,我想使用RegularExpressions匹配字符串..现在我想文本框文本应该匹配只有数字高达3当我按下按钮然后它应该工作... 我正在尝试的是哪个不工作:: -NSString不工作的NSRegularExpression

-(IBAction)ButtonPress{ 

NSString *string =activity.text; 
NSError *error = NULL; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]{1,3}$" options:NSRegularExpressionCaseInsensitive error:&error]; 
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""]; 

if ([activity.text isEqualToString:modifiedString ]) 
{ // work only if this matches numeric value from the text box text 
}} 
+0

你到底要什么来实现呢?只允许数字最大999,或只有0,1,2和3? – JustSid

+0

只有999个数字 – Christien

回答

2
- (BOOL)NumberValidation:(NSString *)string { 
    NSUInteger newLength = [string length]; 
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"1234567890"] invertedSet]; 
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; 
    return (([string isEqualToString:filtered])&&(newLength <= 3)); 
} 

在您的按钮操作事件只是用这个像波纹管......

-(IBAction)ButtonPress{ 

if ([self NumberValidation:activity.text]) { 
     NSLog(@"Macth here"); 
    } 
    else { 
     NSLog(@"Not Match here"); 
    } 
} 
+0

@Christien你好兄弟..检查这个代码,现在我在我的应用软件测试.. :) –

+0

helloss bro ..gm :)等等等等.. – Christien

+1

ya ryt.got背后的逻辑 – Christien

1

请尝试下面的代码。

- (BOOL) validate: (NSString *) candidate { 
    NSString *digitRegex = @"^[0-9]{1,3}$"; 
    NSPredicate *regTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", digitRegex]; 
    return [regTest evaluateWithObject:candidate]; 
} 

-(IBAction)btnTapped:(id)sender{ 

    if([self validate:[txtEmail text]] ==1) 
    { 
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"You Enter Correct id." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil]; 
     [alert show]; 
     [alert release]; 

    } 
    else{ 
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"You Enter Incoorect id." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil]; 
     [alert show]; 
     [alert release]; 
    } 
} 
2

你的代码替换所有比赛用一个空字符串,因此,如果有匹配,它会通过一个空字符串代替,你的支票不会有任何效果。相反,只是问的正则表达式的第一场比赛的范围:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]{1,3}$" options:NSRegularExpressionCaseInsensitive error:NULL]; 
NSRange range = [regex rangeOfFirstMatchInString:string options:0 range:NSMakeRange(0, [string length])]; 

if(range.location != NSNotFound) 
{ 
    // The regex matches the whole string, so if a match is found, the string is valid 
    // Also, your code here 
} 

您也可以只要求匹配的数量,如果不是零,该字符串包含0999之间的数字,因为你的正则表达式匹配整个字符串。