如何使用 NSRegularExpression 删除括号内的文本?
How to remove text within parentheses using NSRegularExpression?
我尝试删除括号内的部分字符串。
例如,对于字符串"(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);
删除正则表达式定界符并确保您也排除字符 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);
看到这个IDEONE demo and a regex demo。
\([^()]+\)
模式将匹配
\(
- 左括号
[^()]+
- (
和 )
以外的 1 个或多个字符(将 +
更改为 *
以匹配并删除空括号 ()
)
\)
- 右括号
我尝试删除括号内的部分字符串。
例如,对于字符串"(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);
删除正则表达式定界符并确保您也排除字符 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);
看到这个IDEONE demo and a regex demo。
\([^()]+\)
模式将匹配
\(
- 左括号[^()]+
-(
和)
以外的 1 个或多个字符(将+
更改为*
以匹配并删除空括号()
)\)
- 右括号