| Author |
Java regex for removing brackets
|
Devaka Cooray
Saloon Keeper
Joined: Jul 29, 2008
Posts: 2694
|
|
Consider the following String
String s= "copy (x copy(y,z), left(s,4) ) and update(m)";
Any idea of removing every bracketed expression from the above String, using regular expressions? I need the final result as
"copy (x copy(y,z), left(s,4) ) and update(m)". I'm wondering to do that with String.replaceAll(String,String) method, but couldn't make an appropriate regular expression for that.
I know we can simply do that by manually coding it with loops and conditions. Just interested to know if it is possible to do so with regular expressions. Any thoughts?
|
Author of ExamLab (Download) - the free mock exam kit for SCJP / OCPJP
Home Page -- Twitter Profile -- JavaRanch FAQ -- How to Ask a Question
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16695
|
|
Doing it in a single pass will not be easy with regex. This is due to the "nested" requirement. This is not to say it is impossible, though.
One option, is to not deal with the "nested" requirement. And run it through many passes.
s.replaceAll("\\([^\\(]*\\)", "");
After one pass.... "copy (x copy(y,z), left(s,4) ) and update(m)";
After two pass.... "copy (x copy(y,z), left(s,4) ) and update(m)";
But personally, it is probably easier to just not use regex. By keeping a count, of the depth of the nests, as you parse, you can do it in a single pass.
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Devaka Cooray
Saloon Keeper
Joined: Jul 29, 2008
Posts: 2694
|
|
Thanks Henry, that's a good suggestion.
The given regex didn't work properly but it worked after a small modification as "\\([^\\(^\\)]*\\)"
Thanks again,
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16695
|
|
Devaka Cooray wrote:
The given regex didn't work properly but it worked after a small modification as "\\([^\\(^\\)]*\\)"
Oops... forgot to mention that I didn't actually try it out...
BTW, I didn't try this one out either...
s.replaceAll("\\([^\\(]*?\\)", "");
Henry
|
 |
Devaka Cooray
Saloon Keeper
Joined: Jul 29, 2008
Posts: 2694
|
|
Henry Wong wrote:s.replaceAll("\\([^\\(]*?\\)", "");
I just forgot to use that reluctant quantifier
Both "\\([^\\(^\\)]*\\)" and "\\([^\\(]*?\\)" works properly.
Devaka
|
 |
Carey Brown
Ranch Hand
Joined: Nov 19, 2001
Posts: 159
|
|
FYI The back slashes in the character class are not required in your case. Hence, a slightly cleaner version would be:
"\\([^()]*\\)" and "\\([^(]*?\\)"
Cheers.
|
 |
 |
|
|
subject: Java regex for removing brackets
|
|
|