objective-c - 如何使用 NSRegularExpression 删除括号内的文本?

标签 objective-c regex nsregularexpression

我尝试删除括号内的部分字符串。

例如,对于字符串"(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 demoa regex demo .

\([^()]+\) 模式将匹配

  • \( - 左括号
  • [^()]+ - () 以外的 1 个或多个字符(更改 +* 也匹配并删除空括号 ())
  • \) - 右括号

关于objective-c - 如何使用 NSRegularExpression 删除括号内的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36938981/

相关文章:

iphone - Sharekit 无法在 Facebook 上运行

ios - 列出创建的类的所有实例

python - 动态拆分Python中的复杂字符串

regex - 如何为由URL stub 中动态生成的数字组成的URL设置分析目标?

ios - 创建一个 NSRange 的 NSMutableArray 并稍后正确读取范围值

ios - NS正则表达式组(匹配项)

iphone - 多线程和 “just leaking”警告

ios - 从 UITableView 播放视频

java - 在 Java 中构造正则表达式

ios - 文本中只允许 2 个空格