2013-01-09 67 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之間的數字,因爲你的正則表達式匹配整個字符串。