[英]iPhone: regular expression and text input validation in UITextField is failing
I have the following code thats supposed to take the input entered into a UITextField and validate it. 我有以下代码,它们应该将输入输入到UITextField并验证它。 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" 该字符串应该不能通过正则表达式测试:“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. 该方法
numberOfMatchesInString:
在字符串中匹配搜索。 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 string Einxnkxkd Xnckck
yielding Einxnk
. 它正在传递,因为模式
([0-9a-zA-Z\\\\s]{1,6})
至少匹配测试字符串Einxnkxkd Xnckck
的前六个字母,产生Einxnk
。 In fact, I can find lots of matches: E
, Ein
, inx
, etc. 事实上,我可以找到很多比赛:
E
, Ein
, inx
等。
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})$
. 如果要确保整个字符串与模式匹配,请使用
^
表示字符串的开头,并使用$
标记结束,以便您的模式变为^([0-9a-zA-Z\\\\s]{1,6})$
。
If you want to limit the expression to exactly the string, you need to wrap the expression in ^..$: 如果要将表达式限制为字符串,则需要将表达式包装在^ .. $中:
NSString *const regularExpression = @"^([0-9a-zA-Z\\s]{1,6})$";
Edit : Use the RegEx Air app to test, it's pretty handy (or any other reg exp tester) 编辑 :使用RegEx Air应用程序进行测试,它非常方便(或任何其他reg exp测试仪)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.