我是个十足的新手。我正试图想出一个正则表达式来捕捉大括号中的文本。示例:
{t} this text shouldn't {1}{2} be captured {3} -> t, 1, 2, 3这就是我尝试过的:
NSString *text = @"{t} this text shouldn't {1}{2} be captured {3}";
NSString *pattern = @"\\{.*\\}"; // The part I need help with
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:kNilOptions
error:nil];
NSArray *matches = [regex matchesInString:text
options:kNilOptions
range:NSMakeRange(0, text.length)];
for (NSTextCheckingResult *result in matches)
{
NSString *match = [text substringWithRange:result.range];
NSLog(@"%@%@", match , (result == matches.lastObject) ? @"" : @", ");
}产生了{t} this text shouldn't {1}{2} be captured {3}。
对于这么简单的请求,我很抱歉,但我只是很匆忙,我对regexes不太了解。
发布于 2014-07-21 08:34:00
向前看和向后看
NSRegularExpressions支持查找器,因此我们可以使用这个简单的正则表达式:
(?<=\{)[^}]+(?=\})参见regex演示中的匹配。
若要迭代所有匹配,请使用以下命令:
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=\\{)[^}]+(?=\\})" options:NSRegularExpressionAnchorsMatchLines error:&error];
NSArray *matches = [regex matchesInString:subject options:0 range:NSMakeRange(0, [subject length])];
NSUInteger matchCount = [matches count];
if (matchCount) {
for (NSUInteger matchIdx = 0; matchIdx < matchCount; matchIdx++) {
NSTextCheckingResult *match = [matches objectAtIndex:matchIdx];
NSRange matchRange = [match range];
NSString *result = [subject substringWithRange:matchRange];
}
}
else { // Nah... No matches.
}解释
(?<=\{)断言,当前位置之前的是一个开口大括号[^}]+匹配所有不是结束大括号的字符。(?=\})断言下面是一个结束大括号参考
https://stackoverflow.com/questions/24860703
复制相似问题