2014-05-13 43 views
1

我试图解析使用NSRegularExpression一个字符串,这样我就可以在预定义的短语之间抽取几个字符串的字符串:解析使用NSRegularExpression

NSString* theString = @"the date is February 1st 2000 the place is Los Angeles California the people are Peter Smith and Jon Muir"; 
NSString *pattern = @"(?:the date is)(.*?)(?: the place is)(.*?)(?: the people are)(.*?)"; 

NSError *error = nil; 

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error]; 


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

我期待拿到3场比赛:

2月1日2000 加利福尼亚州洛杉矶 Peter Smith和Jon Muir

但是看起来我并没有正确地放置正则表达式组。任何建议?

回答

1

选择1:小组赛

the date is\s*(.*?)\s*the place is\s*(.*?)\s*the people are (.*) 

demo(在右下窗格中确保看组

可以进一步当然微调。 :)

的想法是,括号捕捉你想要的文字到第1组,第2组和第3组。

This question给人的语法来检索组的想法在Objective C.

匹配选项2:直匹配,使用lookarounds

有点更笨重:

(?<=the date is).*?(?=\s*the place is)|(?<=the place is).*?(?=\s*the people are)|(?<=the people are).* 

请参阅demo

+0

这很好,谢谢。我特别喜欢这个网站。 – mishod