4

I try to remove part of the string which is inside parentheses.

As an example, for the string "(This should be removed) and only this part should remain", after using NSRegularExpression it should become "and only this part should remain".

I have this code, but nothing happens. I have tested my regex code with RegExr.com and it works correctly. I would appreciate any help.

NSString *phraseLabelWithBrackets = @"(test text) 1 2 3 text test";
NSError *error = NULL;
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:@"/\\(([^\\)]+)\\)/g" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *phraseLabelWithoutBrackets = [regexp stringByReplacingMatchesInString:phraseLabelWithBrackets options:0 range:NSMakeRange(0, [phraseLabelWithBrackets length]) withTemplate:@""];
NSLog(phraseLabelWithoutBrackets);
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Bastek
  • 899
  • 1
  • 12
  • 27
  • 1
    Check this. http://stackoverflow.com/questions/3741279/how-do-you-remove-parentheses-words-within-a-string-using-nsregularexpression?rq=1 – Ruchira Randana Apr 29 '16 at 13:02

1 Answers1

6

Remove the regex delimiters and make sure you also exclude ( in the character class:

NSString *phraseLabelWithBrackets = @"(test text) 1 2 3 text test";
NSError *error = NULL;
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:@"\\([^()]+\\)" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *phraseLabelWithoutBrackets = [regexp stringByReplacingMatchesInString:phraseLabelWithBrackets options:0 range:NSMakeRange(0, [phraseLabelWithBrackets length]) withTemplate:@""];
NSLog(phraseLabelWithoutBrackets);

See this IDEONE demo and a regex demo.

The \([^()]+\) pattern will match

  • \( - an open parenthesis
  • [^()]+ - 1 or more characters other than ( and ) (change + to * to also match and remove empty parentheses ())
  • \) - a closing parenthesis
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563