Ios NSRegularExpression:如何从NSString中提取匹配的组?
我的代码看起来像Ios NSRegularExpression:如何从NSString中提取匹配的组?,ios,objective-c,regex,nsregularexpression,Ios,Objective C,Regex,Nsregularexpression,我的代码看起来像 NSString *pattern = @"\\w+(\\w)"; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil]; NSString *testValue
NSString *pattern = @"\\w+(\\w)";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive error:nil];
NSString *testValue = @"Beer, Wine & Spirits (beer_and_wine)";
NSTextCheckingResult *match = [regex firstMatchInString:testValue options:0 range:NSMakeRange(0, testValue.length)];
for (int groupNumber=1; groupNumber<match.numberOfRanges; groupNumber+=1) {
NSRange groupRange = [match rangeAtIndex:groupNumber];
if (groupRange.location != NSNotFound)
NSLog(@"match %d: '%@'", groupNumber, [testValue substringWithRange:groupRange]);
else
NSLog(@"match %d: '%@'", groupNumber, @"");
}
我想提取啤酒和葡萄酒
我得到了什么?当我运行此代码时,没有匹配的内容,因此,没有打印出任何内容来匹配啤酒和葡萄酒,您可以使用以下简单的正则表达式:
(?<=\()[^()]*
您的正则表达式不正确,因此它不会像您期望的那样匹配。请尝试以下操作:
NSString *pattern = @"\\((\\w+)\\)";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=\\()[^()]*" options:NSRegularExpressionAnchorsMatchLines error:&error];
if (regex) {
NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:subject options:0 range:NSMakeRange(0, [subject length])];
if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) {
NSString *result = [string substringWithRange:rangeOfFirstMatch];
} else {
// no match
}
} else {
// there's a syntax error in the regex
}
NSString *pattern = @"\\((\\w+)\\)";