【问题标题】:How to remove text within parentheses using NSRegularExpression?如何使用 NSRegularExpression 删除括号内的文本?
【发布时间】:2016-08-24 15:40:11
【问题描述】:

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

例如,对于字符串"(This should be removed) and only this part should remain",在使用NSRegularExpression 后它应该变成"and only this part should remain"

我有这段代码,但没有任何反应。我已经用 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);

【问题讨论】:

标签: objective-c regex nsregularexpression


【解决方案1】:

删除正则表达式分隔符并确保您还在字符类中排除 (

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 个或多个字符(将+ 更改为* 以匹配并删除空括号()
  • \) - 右括号

【讨论】:

    猜你喜欢
    • 2015-10-05
    • 1970-01-01
    • 2011-04-14
    • 2013-11-17
    • 2019-10-29
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    相关资源
    最近更新 更多