Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression syntax in Objective-C

I have looked everywhere and can't find a solution that works for this.

I have:

- (BOOL) textFieldShouldEndEditing:(UITextField *)textField {
    NSString *regEx = @"/^[1-9]\d*(\.\d+)?$/";
    NSRange r = [textField.text rangeOfString:regEx options:NSRegularExpressionSearch];

    if (r.location == NSNotFound) {
        UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Entry Error"
                                                     message:@"Enter only numbers or decimals"         
                                                    delegate:self 
                                           cancelButtonTitle:@"OK"
                                           otherButtonTitles:nil];
        [av show];

        return NO;
    } else {
        return YES;
    }
}

But the regular expression isn't working. I want it to only accept numbers and decimals. I know that there is some weird difference in code with regex where you have to double up on backslashes or something, but I couldn't figure it out.

like image 819
user1066524 Avatar asked Aug 27 '26 22:08

user1066524


1 Answers

Remove the [1-9] at the beginning as well as the forward slashes and escape the backslashes so it is just:

 "^\\d*(\\.\\d+)?$"

See How can I escape this regex properly in Objective-C?

like image 87
Nathan Villaescusa Avatar answered Aug 30 '26 13:08

Nathan Villaescusa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!