我不太熟悉正则表达式,因此我一直在使用Apple的NSRegularExpression
我想删除括号或括号中的单词...
例如:
NSString*str = @"你如何(删除括号中的单词)使用"
结果字符串应该是:@"你如何在一个字符串中使用"
谢谢!!!
搜索
\([^()]*\)
Run Code Online (Sandbox Code Playgroud)
并且什么也没有替换.
作为一个冗长的正则表达式:
\( # match an opening parenthesis
[^()]* # match any number of characters except parentheses
\) # match a closing parenthesis
Run Code Online (Sandbox Code Playgroud)
如果括号正确平衡并且无法使用,这将正常工作.如果括号可以嵌套(like this (for example)),那么你需要重新运行替换,直到没有进一步的匹配,因为在每次运行中只匹配最里面的括号.*
要删除括号,执行相同的操作\[[^[\]]*\],对大括号\{[^{}]*\}.
使用条件表达式,你可以同时做三个,但正则表达式看起来很难看,不是吗?
(?:(\()|(\[)|(\{))[^(){}[\]]*(?(1)\))(?(2)\])(?(3)\})
Run Code Online (Sandbox Code Playgroud)
但是,我不确定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.
Run Code Online (Sandbox Code Playgroud)
*你不能使用正则表达式匹配任意嵌套的括号(因为这些结构不再是常规的),所以这不是对这个正则表达式的限制,而是一般的正则表达式.
| 归档时间: |
|
| 查看次数: |
3803 次 |
| 最近记录: |