25

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?

james.garriss
  • 12,959
  • 7
  • 83
  • 96
Lily
  • 5,872
  • 19
  • 56
  • 75

4 Answers4

47

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

For example:

"\\(.+?\\)"
jjnguy
  • 136,852
  • 53
  • 295
  • 323
17
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

Andreas Panagiotidis
  • 2,763
  • 35
  • 32
11

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:

String regex = "\\([^)]*\\)";
iammichael
  • 9,477
  • 3
  • 32
  • 42
4
String foo = "bar (baz)";
String boz = foo.replaceAll("\\(.+\\)", ""); // or replaceFirst

boz is now "bar "

Greg Mattes
  • 33,090
  • 15
  • 73
  • 105