Capturing parentheses using regex on iphone

Trying to get the url from some HTML that I am processing (on the iPhone) using “grab brackets” to just group the bit of interest to me.

Now I have this:

NSString *imageHtml;  //a string with some HTML in it

NSRegularExpression* innerRegex = [[NSRegularExpression alloc] initWithPattern:@"href=\"(.*?)\"" options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators error:nil];
NSTextCheckingResult* firstMatch = [innerRegex firstMatchInString:imageHtml options:0 range:NSMakeRange(0, [imageHtml length])];
[innerRegex release];

if(firstMatch != nil)
{
    newImage.detailsURL = 
    NSLog(@"found url: %@", [imageHtml substringWithRange:firstMatch.range]);
}

The only thing he lists is a complete match (like this: href = "http://tralalala.com" instead of http://tralalala.com

How can I make it only return my first parentheses?

+3
source share
2 answers

Regex , 0, 1. NSTextCheckingResult . , , , .

NSString *imageHtml = @"href=\"http://tralalala.com\"";  //a string with some HTML in it

NSRegularExpression* innerRegex = [[NSRegularExpression alloc] initWithPattern:@"href=\"(.*?)\"" options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators error:nil];
NSTextCheckingResult* firstMatch = [innerRegex firstMatchInString:imageHtml options:0 range:NSMakeRange(0, [imageHtml length])];
[innerRegex release];

if(firstMatch != nil)
{
    //The ranges of firstMatch will provide groups, 
    //rangeAtIndex 1 = first grouping
    NSLog(@"found url: %@", [imageHtml substringWithRange:[firstMatch rangeAtIndex:1]]);
}
+6

:

(?<=href=\")(.*?)(?=\")
0

All Articles