NSString *searchText = @" @+861345678888-昵称 大富翁收到";
NSString *regexStr = @" @(\\+\\d+)-(.*) ";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *matches = [regex matchesInString:searchText
options:0
range:NSMakeRange(0, [searchText length])];
if (matches.count>0) {
//此方法只能获取一个整体的正则匹配
for (NSTextCheckingResult *match in matches) {
NSRange matchRange = [match range];
NSString *matchString = [searchText substringWithRange:matchRange];
NSLog(@"%@", matchString);
}
//捕获组用以下方法
NSRange matchRange = [[matches firstObject] rangeAtIndex:1];
NSString *matchString = [searchText substringWithRange:matchRange];
NSLog(@"%@", matchString);
NSRange matchRange2 = [[matches firstObject] rangeAtIndex:2];
NSString *matchString2 = [searchText substringWithRange:matchRange2];
NSLog(@"%@", matchString2);
}
/*
2019-03-07 15:49:59.505905+0800 Demo[27094:6786924] @+861345678888-昵称
2019-03-07 15:49:59.506050+0800 Demo[27094:6786924] +861345678888
2019-03-07 15:49:59.506173+0800 Demo[27094:6786924] 昵称
*/
[iOS]正则匹配捕获组
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。