Maneesh Sharma Maneesh Sharma - 14 days ago 5
iOS Question

Validate a string using regex

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.

Answer

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.

Comments