在iOS中,我需要根据正则表达式检查字符串,如果字符串通过则返回true
(例如),否则返回false
。我了解我必须使用NSRegularExpression
类,但是我不知道如何使用。
您应该阅读文档。
以下是示例代码,通常如何执行此操作:
- (BOOL)checkString:(NSString *)string {
NSString *const expression = @"^\\d{3}[-]\\d{2}[-]\\d{4}$"; // insert yours
NSError *error = nil;
NSRegularExpression * const regExpr =
[NSRegularExpression regularExpressionWithPattern:expression
options:NSRegularExpressionCaseInsensitive
error:&error];
NSTextCheckingResult * const matchResult = [regExpr firstMatchInString:string
options:0 range:NSMakeRange(0, [string length])];
return matchResult ? YES : NO;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句