正则表达式替换括号()之间的内容
我尝试了这段代码:
string.replaceAll("\\(.*?)","");
但它返回 null。我缺少什么?
I tried this code:
string.replaceAll("\\(.*?)","");
But it returns null. What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试:
您没有转义第二个括号,也没有在第一个括号中添加额外的“\”。
Try:
You didn't escape the second parenthesis and you didn't add an additional "\" to the first one.
首先,您要删除括号及其内容吗?尽管问题的标题表明“否”,但我假设您也确实希望删除括号。
其次,括号之间的内容可以包含嵌套匹配的括号吗?该解决方案假设是。由于 Java 正则表达式风格不支持递归表达式,因此解决方案是首先制作一个与“最里面”括号集匹配的正则表达式,然后以迭代方式应用该正则表达式,从内到外替换它们。这是一个经过测试的 Java 程序,它正确删除(可能是嵌套的)括号及其内容:
测试输入:
测试输出:
请注意,lazy-dot-star 解决方案永远不会工作,因为在嵌套时它无法匹配最里面的一组括号。 (即它错误地匹配:上面示例中的
(foo1(bar1)
。)这是一个非常常见的正则表达式错误:永远不要在存在时使用点是一个更精确的表达式!在这种情况下,“最里面”的一组匹配括号之间的内容由任何不是左括号或右括号的字符组成,(即使用:[^()]*
而不是:.*?
)。First, Do you wish to remove the parentheses along with their content? Although the title of the question indicates no, I am assuming that you do wish to remove the parentheses as well.
Secondly, can the content between the parentheses contain nested matching parentheses? This solution assumes yes. Since the Java regex flavor does not support recursive expressions, the solution is to first craft a regex which matches the "innermost" set of parentheses, and then apply this regex in an iterative manner replacing them from the inside-out. Here is a tested Java program which correctly removes (possibly nested) parentheses and their contents:
Test Input:
Test Output:
Note that the lazy-dot-star solution will never work, because it fails to match the innermost set of parentheses when they are nested. (i.e. it erroneously matches:
(foo1(bar1)
in the example above.) And this is a very commonly made regex mistake: Never use the dot when there is a more precise expression! In this case, the contents between an "innermost" set of matching parentheses consists of any character that is not an opening or closing parentheses, (i.e. Use:[^()]*
instead of:.*?
).尝试
string.replaceAll("\\(.*?\\)","")
。Try
string.replaceAll("\\(.*?\\)","")
.string.replaceAll("\\([^\\)]*\\)","");
这样你就可以说匹配一个括号,然后是所有非右括号字符,然后是一个右括号。这通常比不情愿或贪婪的 .* 匹配器更快。
string.replaceAll("\\([^\\)]*\\)","");
This way you are saying match a bracket, then all non-closing bracket chars, and then a closing bracket. This is usually faster than reluctant or greedy .* matchers.