ios - NSRegularExpression: How to extract matched group from NSString? -



ios - NSRegularExpression: How to extract matched group from NSString? -

my code looks

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)]; (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 want do?

nsstring *testvalue = @"beer, wine & spirits (beer_and_wine)";

i want extract beer_and_wine

what get? when run code, nil matched , nil printed out

to match beer_and_wine, can utilize simple regex:

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

see demo.

the (?<=\() lookbehind checks preceded opening parenthesis [^()]* matches characters not parentheses

in code, 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 syntax error in regex }

ios objective-c regex nsregularexpression

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -