iOS NSRegularExpression如何找到第一个匹配的“TAIL”模式如:HEAD(。*)TAIL

时间:2014-03-14 07:37:14

标签: ios regex

例如:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"hello: (.*)ABC" options:0 error:NULL];
NSString *str = @"hello: bobABC123ABC";
NSTextCheckingResult *match = [regex firstMatchInString:str options:0 range:NSMakeRange(0, [str length])];
NSLog(@"macthing part is %@", [str substringWithRange:[match rangeAtIndex:0]]);

匹配的结果是" bobABC123ABC",所以匹配" ABC"在NSRegularExpression中找到最后一个" ABC"在字符串而不是第一个。 我希望匹配是" bob",任何人都知道如何实现这个目标吗?

1 个答案:

答案 0 :(得分:1)

让你正常表达非贪婪。说:

@"hello: (.*?)ABC"
            ^
            |==> note this

而不是

@"hello: (.*)ABC"

来自documentation

  

*?匹配0次或更多次。匹配尽可能少的次数。