Bas*_*tek 4 regex objective-c 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);
Run Code Online (Sandbox Code Playgroud)
删除正则表达式分隔符,并确保您还在(字符类中排除:
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);
Run Code Online (Sandbox Code Playgroud)
该\([^()]+\)模式将匹配
\( - 一个开括号[^()]+-比其它1个或多个字符(和) (变化+到*为了匹配并取出空括号())\) - 右括号