检查NSString是否包含任何数字,且长度至少为7个字符 [英] Check if NSString contains any numbers and is at least 7 characters long
问题描述
所以我想我需要一个正则表达式语句才能做到这一点,但我还没有用目标c做任何正则表达式,而且我还没有在一年内编写正则表达式语句。
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.
我认为应该是((?=。* [0-9])。{7,1000})
I think it should be like ((?=.*[0-9]).{7,1000})
如何我把它放到一个客观的c字符串比较中并评估结果?
How do I put this into an objective c string comparison and evaluate the results?
我的正则表达式是否正确?
Also is my regex correct?
推荐答案
虽然正则表达式可能有效,但还有另一种方法:
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
}
此代码实际上检查不仅仅是0-9。它也处理来自其他语言的数字。如果你真的只想要0-9然后替换:
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"];
这篇关于检查NSString是否包含任何数字,且长度至少为7个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!