Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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?

like image 622
Lily Avatar asked Sep 07 '25 14:09

Lily


2 Answers

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

For example:

"\\(.+?\\)"
like image 73
jjnguy Avatar answered Sep 09 '25 05:09

jjnguy


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

My code is based on previous answers

like image 27
Andreas Panagiotidis Avatar answered Sep 09 '25 03:09

Andreas Panagiotidis