在Objective C中,常用的正则表达式有:
- 匹配数字:\d
例如:NSString *regex = @"\d+";
- 匹配字母:[a-zA-Z]
例如:NSString *regex = @"[a-zA-Z]+";
- 匹配邮箱:\w+([-+.]\w+)@\w+([-.]\w+).\w+([-.]\w+)*
例如:NSString regex = @"\w+([-+.]\w+)@\w+([-.]\w+)\.\w+([-.]\w+)";
- 匹配手机号码:1[3-9]\d{9}
例如:NSString *regex = @"1[3-9]\d{9}";
- 匹配身份证号码:\d{17}[\dxX]
例如:NSString *regex = @"\d{17}[\dxX]";
示例代码如下:
NSRegularExpression *reg = [[NSRegularExpression alloc] initWithPattern:regex options:NSRegularExpressionCaseInsensitive error:nil];
NSTextCheckingResult *result = [reg firstMatchInString:str options:NSMatchingReportCompletion range:NSMakeRange(0, [str length])];
if (result) {
// 匹配到了
} else {
// 没有匹配到
}
其中,regex为上述正则表达式,str为要匹配的字符串,result为匹配结果对象。使用NSRegularExpression类的firstMatchInString方法可以获取匹配结果。