views:

137

answers:

2

Please consider the following:

NSString *myText = @"mary had a little lamb";
NSString *regexString = @"mary(.*?)little";

for(NSString *match in [myText captureComponentsMatchedByRegex:regexString]){

NSLog(@"%@",match);

}

This will output to the console two things:

1) "mary had a little" 2) "had a"

What I want is just the 2nd bit of information "had a". Is there is a way of matching a string and returning just the inner part?

I'm fairly new to Objective C, this feels a rather trivial question yet I can't find a less messy way of doing this than incrementing an integer in the for loop and on the second iteration storing the "had a" in an NSString.

A: 

With regular expressions, it's standard that the first match returned is the whole matched string ("mary had a little"), then the next items are the captured groups ("had a").

-captureComponentsMatchedByRegex: returns a NSArray of the matches. So, if you want the second item, or the first captured group:

NSString *match = [[myText captureComponentsMatchedByRegex:regexString] objectAtIndex:1]
jtbandes
Perfect, just what I needed.
StuR
A: 

captureComponentsMatchedByRegex: returns all the captures of the first match of the regex. Array index (aka capture) 0 is "all the text matched by the regex". If the regex contains additional capture groups, as your regex does, those array indexes begin at 1 and continue for as many capture groups that are present in the regex.

What you probably want is the componentsMatchedByRegex:capture: method. This method returns an array of all the matches in the string it is sent to and additionally allows you to specify which capture group is used to create the array of results. For example:

NSString *myText = @"mary had a little lamb";
NSString *regexString = @"mary(.*?)little";

for(NSString *match in [myText componentsMatchedByRegex:regexString capture:1L]) {
  NSLog(@"%@",match);
}

The above will print just " had a ".

johne