daydreamer
daydreamer

Reputation: 91969

NSRegularExpression: How to extract matched group from NSString?

My code looks like

    NSString *pattern = @"\\w+(\\w)";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
                                 options:NSRegularExpressionCaseInsensitive error:nil];
    NSString *testValue = @"Beer, Wine & Spirits (beer_and_wine)";
    NSTextCheckingResult *match = [regex firstMatchInString:testValue options:0 range:NSMakeRange(0, testValue.length)];
    for (int groupNumber=1; groupNumber<match.numberOfRanges; groupNumber+=1) {
        NSRange groupRange = [match rangeAtIndex:groupNumber];
        if (groupRange.location != NSNotFound)
            NSLog(@"match %d: '%@'", groupNumber, [testValue substringWithRange:groupRange]);
        else
            NSLog(@"match %d: '%@'", groupNumber, @"");
    }

What I want to do?
From

NSString *testValue = @"Beer, Wine & Spirits (beer_and_wine)";

I want to extract beer_and_wine

What I get?
When I run this code, nothing it matched so , nothing is printed out

Upvotes: 1

Views: 272

Answers (2)

hwnd
hwnd

Reputation: 70732

Your regular expression is incorrect, so it will not match as you expect. Try the following:

NSString *pattern = @"\\((\\w+)\\)";

Upvotes: 1

zx81
zx81

Reputation: 41838

To match beer_and_wine, you can use this simple regex:

(?<=\()[^()]*

See demo.

  • The (?<=\() lookbehind checks that we are preceded by an opening parenthesis
  • [^()]* matches any characters that are not parentheses

In code, something like this:

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=\\()[^()]*" options:NSRegularExpressionAnchorsMatchLines error:&error];
if (regex) {
    NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:subject options:0 range:NSMakeRange(0, [subject length])];
    if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) {
        NSString *result = [string substringWithRange:rangeOfFirstMatch];
    } else {
        // no match
    }
} else {
    // there's a syntax error in the regex
}

Upvotes: 2

Related Questions