NSRegularExpression - 匹配多个字符串

时间:2014-07-15 07:36:28

标签: regex nsregularexpression

基本上,我的字符串看起来像这样:

@"{{attendee.prefix}} {{attendee.firstname}} {{attendee.lastname}}, fwf<br /><span style="font-size:14px;">lalallasgabab {{attendee.weg2g}} {{attendee.5236t2gsg}}  {{attendee.ticket_no}}  agagawfbeagabs</span>"

我正在尝试提取由2个大括号封装的所有字符串:

[ {{attendee.prefix}}, {{attendee.firstname}}, {{attendee.lastname}}, {{attendee.weg2g}}, {{attendee.5236t2gsg}}, {{attendee.ticket_no}} ]

我试过这些正则表达式,但如果不是整个字符串,它总是会返回1个匹配。

@"(\\{\\{.*\\}\\})" - &gt;返回整个字符串

@"\\{\\{[^}]*+\\}\\}" - &gt;只匹配{{attendee.firstname}}

@"\\b\\{\\{[^}]*+\\}\\}\\b" - &gt;仅匹配{{attendee.prefix}}

这是我的代码:

NSString *myString = @"{{attendee.prefix}} {{attendee.firstname}} {{attendee.lastname}}, fwf<br /><span style="font-size:14px;">lalallasgabab {{attendee.weg2g}} {{attendee.5236t2gsg}}  {{attendee.ticket_no}}  agagawfbeagabs</span>"

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\{\\{[^}]*+\\}\\}" options:NSRegularExpressionCaseInsensitive error:nil];

NSRange visibleTextRange = NSMakeRange(0, myString.length);

NSArray *matches = [regex matchesInString:myString options:NSMatchingAnchored range:visibleTextRange];

for (NSTextCheckingResult *match in matches)
{
    NSLog(@"%@: Match - %@", [self class], [myString substringWithRange:match.range]);
}

我尝试过使用[match rangeAtIndex:index],但仍然会返回相同的内容,有时它超出范围,因为匹配结果只有1。

在这里感谢任何帮助。感谢。

PS:我是Objective-C和RegEx的新手,所以请原谅这个问题。

2 个答案:

答案 0 :(得分:1)

要迭代{{this}}等所有匹配项,请使用:

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\{\\{[^}]*\\}\\}" options:0 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.
     }

答案 1 :(得分:0)

我设法通过使用不同的方法来回答我自己的问题:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\{\\{[^}]*+\\}\\}" options:NSRegularExpressionCaseInsensitive error:nil];

NSString *myString = @"{{attendee.prefix}} {{attendee.firstname}} {{attendee.lastname}}, fwf<br /><span style='font-size:14px;'>lalallasgabab {{attendee.weg2g}} {{attendee.5236t2gsg}}  {{attendee.ticket_no}}  agagawfbeagabs</span>";

[regex enumerateMatchesInString:myString
                        options:0
                          range:NSMakeRange(0, [myString length])
                     usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
                         NSLog(@"%@: Match - %@", [self class], [self.duplicateBody substringWithRange:result.range]);
                     }];

通过上面的代码,我能够遍历每个匹配的字符串,这正是我想要的。