2

It's the first time trying to use Regular Expression. I am trying to match Australian Post code(i.e 4 digit) , but my noOFMatches gets no . of digits +1 (9 in this case)in it. I know it's something silly that i cannot figure out. Pls suggest. I feel if I pass 4 digit nos. in postcode then noOfMatches should get 1 . is that correct?

  NSString *postCode = @"12345676";
    NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:@"(|d{4})" options:NSRegularExpressionCaseInsensitive error:nil];

  int noOfMatches = [ regularExpression numberOfMatchesInString:field.text options:0 range:NSMakeRange(0,  [postCode length])];

2 Answers 2

4

You're on the right track, although the pattern you've used isn't correct and that's why it returns 9 matches.

It's an easy fix:

([0-9]{4})

or

(\\d{4})

Should give you the correct result: 2

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

Comments

0

You should use a regex tester, eg http://regexpal.com/

Native iOS regex is ridiculously clumsy and lengthy. If you work with regex alot, I'd recommend using a library, such as https://github.com/bendytree/Objective-C-RegEx-Categories

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.