2014-03-14 26 views
0

例如:的iOS NSRegularExpression如何找到像图案的第一匹配 “TAIL”:(。*)头尾

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”而不是第一个。 我希望匹配是“鲍勃”,任何人都知道如何实现这一目标?

+0

您只想匹配_bob_或_bobABC_? –

+0

匹配第一个“ABC”而不是最后一个“ABC” –

回答

1

让你的正则表达式非贪婪。你说:的

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

代替

@"hello: (.*)ABC" 

documentation

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

+0

谢谢@devnull,效果很棒! –