How to remove text in parentheses using NSRegularExpression?

I am trying to remove the part of the line that is in parentheses.

As an example, for a 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 checked the 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);
+4
source share
1 answer

Remove the regex separators and make sure that you also exclude (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 demo IDEONE and demo regex .

\([^()]+\)

  • \( -
  • [^()]+ - 1 , ( ) ( + *, ())
  • \) -
+5

All Articles