xcode 正则表达式只允许字符串和数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10979453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 00:33:54  来源:igfitidea点击:

Regular expression to allow only string and number

iphoneobjective-cxcodeipad

提问by Vinod Vishwakarma

I'm making the pattern to check the user can only enter number and string. Please anyone can help me or give some reference. Following is my code. Thnks in advance.

我正在制作模式来检查用户只能输入数字和字符串。请任何人都可以帮助我或提供一些参考。以下是我的代码。提前谢谢。

NSString *regEx =
     @"(?:[a-z0-9!#$%\&'*+/=?\^_`{|}~-]+(?:\.[a-z0-9!#$%\&'*+/=?\^_`{|}"
     @"~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\"
     @"x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
     @"z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5"
     @"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
     @"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21"
     @"-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])";

NSString *strRoadworthyGet=@"vinod123";
NSPredicate *matchPattern =[NSPredicate predicateWithFormat:@"SELF MATCHES %@",regEx];
BOOL resultMatch =[matchPattern evaluateWithObject:strRoadworthyGet];

if(!resultMatch)
  NSLog(@"invalid pattern");

回答by krammer

You can use NSCharacterSet's alphanumericmethod to return check for Letters, Marks and Numbers.

您可以使用 NSCharacterSet 的字母数字方法返回字母、标记和数字的检查。

If you want to go for RegularExpression, you can use

如果你想使用正则表达式,你可以使用

NSString *regEx = @"^[a-zA-Z0-9]*$";