如何使用NSRegularExpression删除字符串中的括号单词?

时间:2010-09-18 10:19:02

标签: objective-c regex

我不太熟悉正则表达式,因此我一直在使用Apple的NSRegularExpression

我想删除括号或括号中的单词......

例如:

NSString * str = @“你如何(删除括号中的单词)使用”

结果字符串应该是:@“你如何在字符串中使用”

谢谢你!!!

2 个答案:

答案 0 :(得分:5)

搜索

\([^()]*\)

并替换为零。

作为一个冗长的正则表达式:

\(      # match an opening parenthesis
[^()]*  # match any number of characters except parentheses
\)      # match a closing parenthesis

如果括号正确平衡并且无法使用,这将正常工作。如果括号可以嵌套(like this (for example)),那么你需要重新运行替换,直到没有进一步的匹配,因为在每次运行中只匹配最里面的括号。*

要删除括号,请对\[[^[\]]*\]执行与括号\{[^{}]*\}相同的操作。

使用条件表达式你可以一次完成所有三个,但正则表达式看起来很难看,不是吗?

(?:(\()|(\[)|(\{))[^(){}[\]]*(?(1)\))(?(2)\])(?(3)\})

但是,我不确定NSRegularExpression是否可以处理条件。可能不是。这个怪物的解释:

(?:           # start of non-capturing group (needed for alternation)
 (\()         # Either match an opening paren and capture in backref #1
 |            # or
 (\[)         # match an opening bracket into backref #2
 |            # or
 (\{)         # match an opening brace into backref #3
)             # end of non-capturing group
[^(){}[\]]*   # match any number of non-paren/bracket/brace characters
(?(1)\))      # if capturing group #1 matched before, then match a closing parenthesis
(?(2)\])      # if #2 matched, match a closing bracket
(?(3)\})      # if #3 matched, match a closing brace.

* 你不能使用正则表达式匹配任意嵌套的括号(因为这些结构不再是常规的),所以这不是对这个正则表达式的限制,而是一般的正则表达式。

答案 1 :(得分:2)

我不知道objectice-c正则表达式的味道,但在PCRE中你可以这样做:

s/\[.*?\]|\(.*?\)|\{.*?\}//g

这将用空字符串替换括号或括号之间的所有内容。