I have the following code thats supposed to take the input entered into a UITextField and validate it. It doesn’t seem to be working and Im a little confused as to why.
Could someone give me some advice please?
NSString *const regularExpression = @"([0-9a-zA-Z\\s]{1,6})";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regularExpression options:NSRegularExpressionCaseInsensitive error:&error];
if (error)
{
NSLog(@"error %@", error);
}
NSUInteger numberOfMatches =
[regex numberOfMatchesInString:s options:0 range:NSMakeRange(0, [s length])];
NSLog(@"index = %d", i);
NSLog(@"Value of TextField = %@", s);
NSLog(@"Regular expression is = %@", regularExpression);
if (numberOfMatches <= 0)
{
NSLog(@"Failed regex test ");
}
This string should fail the regular expression test :”Einxnkxkd Xnckck”
But it passed.
im not sure how and why…
Anything obvious Im missing here?
Thanks
The method
numberOfMatchesInString:searches for matches within the string. It does not test your pattern against the entire string.It is passing because the pattern
([0-9a-zA-Z\\s]{1,6})is matching at least the first six letters of your test stringEinxnkxkd XnckckyieldingEinxnk. In fact, I can find lots of matches:E,Ein,inx, etc.If you want to make sure the whole string matches the pattern, use
^to indicate the beginning of the string and$to mark the end of it, so that your pattern becomes^([0-9a-zA-Z\\s]{1,6})$.