Question

I am trying to parse a string using NSRegularExpression so that I can extract several strings in between predefined phrases:

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)];

I am expecting to get 3 matches:

February 1st 2000 Los Angeles California Peter Smith and Jon Muir

However it looks like I am not putting the regex groups properly. Any suggestion?

Was it helpful?

Solution

Option 1: With Group Matches

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

See demo (make sure to look at the Groups in the lower right pane)

It can be tweaked further of course. :)

The idea is that the parentheses capture the text you want into Group 1, Group 2 and Group 3.

This question gives an idea of the syntax to retrieve Group matches in Objective C.

Option 2: Straight Matches, using lookarounds

A bit more unwieldy:

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

See the demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top