Java 如何使用正则表达式替换括号中的字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1138552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:10:23  来源:igfitidea点击:

How can I replace a string in parentheses using a regex?

javaregex

提问by Lily

I have a string:

我有一个字符串:

HLN (Formerly Headline News)

I want to remove everything inside the parens and the parens themselves, leaving only:

我想删除括号内的所有内容和括号本身,只留下:

HLN

I've tried to do this with a regex, but my difficulty is with this pattern:

我试图用正则表达式来做到这一点,但我的困难在于这种模式:

"(.+?)"

When I use it, it always gives me a PatternSyntaxException. How can I fix my regex?

当我使用它时,它总是给我一个PatternSyntaxException. 如何修复我的正则表达式?

采纳答案by jjnguy

Because parentheses are special characters in regexps you need to escape them to match them explicitly.

因为括号是正则表达式中的特殊字符,所以您需要对它们进行转义以明确匹配它们。

For example:

例如:

"\(.+?\)"

回答by iammichael

You could use the following regular expression to find parentheticals:

您可以使用以下正则表达式来查找括号:

\([^)]*\)

the \(matches on a left parenthesis, the [^)]*matches any number of characters other than the right parenthesis, and the \)matches on a right parenthesis.

\(上一个左括号匹配,在[^)]*匹配任何数量比右括号其他字符,而\)上一个右括号匹配。

If you're including this in a java string, you must escape the \characters like the following:

如果您将其包含在 java 字符串中,则必须转义如下\字符:

String regex = "\([^)]*\)";

回答by Greg Mattes

String foo = "bar (baz)";
String boz = foo.replaceAll("\(.+\)", ""); // or replaceFirst

bozis now "bar "

boz就是现在 "bar "

回答by Andreas Panagiotidis

String foo = "(x)()foo(x)()";
String cleanFoo = foo.replaceAll("\([^\(]*\)", "");
// cleanFoo value will be "foo"

The above removes empty and non-empty parenthesis from either side of the string.

以上删除了字符串两侧的空括号和非空括号。

plain regex:

普通正则表达式:

\([^\(]*\)

You can test here: http://www.regexplanet.com/simple/index.html

你可以在这里测试:http: //www.regexplanet.com/simple/index.html

My code is based on previous answers

我的代码基于以前的答案