正则表达式,用于匹配分隔符之间多次出现的字符

时间:2014-07-15 23:29:59

标签: objective-c regex nsregularexpression

我正在尝试使用NSRegularExpression查找由一对%字符分隔的多个子字符串,例如,如果我想从以下内容中提取“%FirstOccurence%enter code here”作为子字符串:

"stuff %FirstOccurence% more stuff" 

然后我可以这样做:

NSString* const pattern = @"[%].+[%]";
NSRegularExpression* regex = [[NSRegularExpression alloc] initWithPattern:pattern
                                                                  options:0
                                                                    error:nil];
NSRange range = NSMakeRange(0, [testData length]);
NSTextCheckingResult *textCheckingResult = [regex firstMatchInString:testData options:0 range: range];

但是如果字符串包含这样的内容:

 "stuff %FirstOccurence% more stuff %Second Occurrence% yet more stuff"

然后我的正则表达式将匹配:"%FirstOccurence% more stuff %Second Occurrence%",即NSTextCheckingResult将包含一个范围。

正则表达式/代码应该使NSTextCheckingResult包含两个范围%FirstOccurence%%Second Occurrence%而不是一个更大的范围?

1 个答案:

答案 0 :(得分:0)

看来你想要调用matchesInString:options:range:返回所有匹配的结果。

NSArray *matches = [regex matchesInString:string
                                  options:0
                                    range:NSMakeRange(0, [string length])];

请参阅https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html#//apple_ref/doc/c_ref/NSRegularExpression