2

I want to validate a string to check if it is alphanumeric and contains "-" and "." with the alphanumeric characters. So I have done something like this to form the regex pattern

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[a-zA-Z0-9\\.\\-]"
                                   options:NSRegularExpressionCaseInsensitive
                                   error:&error];
NSPredicate *regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
BOOL valid = [regexTest evaluateWithObject:URL_Query];

App crashes stating that the regex pattern cannot be formed . Can anyone give me a quickfix to what am i doing wrong? Thanks in advance.

11
  • 1
    Try escaping the dash, like this: [a-zA-Z0-9.\-] Commented Nov 18, 2016 at 12:16
  • But . is the metacharacter ? Commented Nov 18, 2016 at 12:18
  • 1
    - at the end of the character class does not have to be escaped. The regex is valid. However, I'd use ^[a-zA-Z0-9.-]+\\z for this task. Commented Nov 18, 2016 at 12:19
  • In any regex engine I've ever dealt with, the . within a character class does not need to be escaped. The - may, though, since it does have special meaning withing a character class (e.g [A-Z]). Commented Nov 18, 2016 at 12:19
  • If I escape - , The error persists @StevenDoggart Commented Nov 18, 2016 at 12:20

1 Answer 1

3

You must pass a variable of type NSString to the NSPredicate SELF MATCHES:

NSString * URL_Query = @"PAS.S.1-23-";
NSString * regex = @"[a-zA-Z0-9.-]+";
NSPredicate *regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
BOOL valid = [regexTest evaluateWithObject:URL_Query];

See the Objective C demo

Note that you need no anchors with the SELF MATCHES (the regex is anchored by default) and you need to add + to match one or more allows symbols, or * to match 0+ (to also allow an empty string).

You do not need to escape the hyphen at the start/end of the character class, and the dot inside a character class is treated as a literal dot char.

Also, since both the lower- and uppercase ASCII letter ranges are present in the pattern, you need not pass any case insensitive flags to the regex.

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

1 Comment

Let me try .! give me a second

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.