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);
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.