objective c - Regex stringByReplacingMatchesInString -


i'm trying remove non-alphanumeric character within string. tried following code snippet, not replacing appropriate character.

nsstring *thestring = @"\"day's\"";  nserror *error = null; nsregularexpression *regex = [nsregularexpression regularexpressionwithpattern:@"^\\b\\w^\\b" options:nsregularexpressioncaseinsensitive error:&error];  nsstring *newstring = [regex stringbyreplacingmatchesinstring:thestring options:0 range:nsmakerange(0, [thestring length]) withtemplate:@""];  nslog(@"the resulting string %@", newstring); 

since there'e need preserve enclosing quotation marks in string, regex becomes bit complex.

here 1 it:

(?:(?<=^")(\w+))|(?:(?!^")(\w+)(?=.))|(?:(\w+)(?="$)) 

it uses lookbehind , lookahead match quotation marks, without including them in capture group, , hence not deleted in substitution empty string.

the 3 parts handle initial quotation mark, characters in middle , last quotation mark, respectively.

it bit pedestrian , there has simpler way it, haven't been able find it. others welcome chime in!

nsstring *thestring = @"\"day's\"";  nsstring *pattern   = @"(?:(?<=^\")(\\w+))|(?:(?!^\")(\\w+)(?=.))|(?:(\\w+)(?=\"$))";   nserror *error = null; nsregularexpression *regex = [nsregularexpression regularexpressionwithpattern: pattern                                                                         options: 0        // no need specify case insensitive, \w makes irrelevant                                                                          error: &error];  nsstring *newstring = [regex stringbyreplacingmatchesinstring: thestring                                                       options: 0                                                         range: nsmakerange(0, [thestring length])                                                   withtemplate: @""]; 

the (?:) construct creates non-capturing parenthesis, meaning can keep lookbehind (or lookahead) group , "real" capture group without creating actual capture group encapsulating whole parenthesis. without couldn't substitute empty string, or deleted.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -