regex - NSRegularExpression to remove digits within parentheses at the end of a line -


i feel i've exhausted every regex can think of , read every piece of nsregularexpression documentation can hands on, still can't figure out.

i have nsstrings end digit within parentheses (something "blah blah blah (33)". want remove parentheses, whitespace, , digits, if matches @ end of line , if contents of parentheses digits (the previous example "blah blah blah"). regex below close, match if there non-digit characters in regex , match if there more content @ end of string, after parentheses:

  nsarray *teststrings = @[@"hello (2)", @"hello (22)", @"hello (22) a", @"hello (2s)"];    (nsstring *msg in teststrings) {      nserror *error = null;     nsregularexpression* regex = [nsregularexpression regularexpressionwithpattern: @"[\\s\(\\d+\\)$]"                                                                            options: nsregularexpressioncaseinsensitive                                                                              error: &error];      if (!error) {        nslog(@"%lu", [regex numberofmatchesinstring:msg options:0 range:nsmakerange(0, [msg length])]);        nsstring* plaintext = [regex stringbyreplacingmatchesinstring: msg                                                             options: 0                                                               range: nsmakerange(0, [msg length])                                                        withtemplate: @""];        nslog(@"%@", plaintext);     }   } 

below output:

test[93719:10248184] 4 test[93719:10248184] hello test[93719:10248184] 5 test[93719:10248184] hello test[93719:10248184] 6 test[93719:10248184] helloa test[93719:10248184] 4 test[93719:10248184] hellos 

any appreciated!

you should use

\s*\(\d+\)$ 

see demo

in objective-c, decalre @"\\s*\\(\\d+\\)$".

your regex - [\s\(\d+\)$] - encloses subpatterns square brackets creating character class matches 1 character: whitespace, or (, or digit, or +, or ), or $.

so, need remove square brackets, , add * quantifier whitespace shorthand class \s leading whitespace matched.


Comments