Check if NSString contains any numbers and is at least 7 characters long
15,731
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"];
Related videos on Youtube
Author by
RickTheSlick
Updated on July 03, 2022Comments
-
RickTheSlick almost 2 years
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?
-
Davit Siradeghyan almost 9 yearsvery nice and short solution
-
Nishant over 6 yearsWhat about a decimal point in the floating numbers? Will it handle that too?