tags:

views:

2091

answers:

4

I have gone through all related topics here on regex and can't find one that really works for my case.

What I want to do is:

HLN (Formerly Headline News) => HLN

which means: I would replace everything inside the parentheses to be "" (including the parentheses).

My difficulty is how to find the pattern "(.+?)", when I tried it, it always gives me

PatternSyntaxException at (

Look forward to your kind help.

+2  A: 

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

For example:

"\\(.+?\\)"
jjnguy
He might want .+? if there may be several parenthetized pieces.
subtenante
Wups, she.
subtenante
yes, she. I put "?" just in case multiple parenthized case.@jjnguy: thanks for the explaination. It works!
Lily
A: 

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
+1  A: 
String foo = "bar (baz)";
String boz = foo.replaceAll("\\(.+\\)", ""); // or replaceFirst

boz is now "bar "

Greg Mattes
A: 

Hello,

What about inner parenthesis?

Suppose that in the string "something: (bla (aa(b)cc) bla)" I want to get the content of the first parenthesis "bla (aa(b)cc) bla", what include other parenthesis?

Is there an easy way ?

Thanks

I know a dummy way: int index_first_left = str.indexof("("); int index_last_right= str.lastIndexOf(")"); you can extract the string between the index_first_left and index_last_right...
Lily