3

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.

0

1 Answer 1

2

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.