Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if NSString contains any numbers and is at least 7 characters long

So I imagine that I need a regex statement to do this but I haven't had to do any regex with objective c yet, and I haven't written a regex statement in like a year.

I think it should be like ((?=.*[0-9]).{7,1000})

How do I put this into an objective c string comparison and evaluate the results?

Also is my regex correct?

like image 938
thirsty93 Avatar asked Oct 20 '12 03:10

thirsty93


1 Answers

While a regular expression would probably work, there is another approach:

NSString *str = // some string to check for at least one digit and a length of at least 7
if (str.length >= 7 && [str rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]].location != NSNotFound) {
    // this matches the criteria
}

This code actually checks more than just 0-9. It handles digits from other languages too. If you really just want 0-9 then replace:

[NSCharacterSet decimalDigitCharacterSet]

with:

[NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
like image 108
rmaddy Avatar answered Sep 30 '22 00:09

rmaddy