我尝试删除括号内的部分字符串。
例如,对于字符串"(This should be removed) and only this part should remained"
,使用NSRegularExpression后应该变成"and only this part should retain"
。
我有这段代码,但没有任何反应。我已经在 RegExr.com 上测试了我的正则表达式代码,它工作正常。如果有任何帮助,我将不胜感激。
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);
最佳答案
删除正则表达式分隔符,并确保您还排除了字符类中的 (
:
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);
查看此 IDEONE demo和 a regex demo .
\([^()]+\)
模式将匹配
\(
- 左括号[^()]+
-(
和)
以外的 1 个或多个字符(更改+
到*
也匹配并删除空括号()
)\)
- 右括号
关于objective-c - 如何使用 NSRegularExpression 删除括号内的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36938981/