-1

I'm looking to replace everything in between a set of parentheses in java using the replaceAll() method. The problem I'm running into is that in between the set of parentheses are another set so it looks like the following: (stuff here (more stuff) and more stuff) and using the regular expression: \\(.*?\\) doesn't work because it ends up only replacing part of it because of the nested parentheses. Any suggestions on a regex I could use to replace everything?

Scoopta
  • 987
  • 1
  • 9
  • 22
  • What output do you want?"(stuff here (more stuff) and more stuff)" to "(stuff here and more stuff)"? – SMA Jan 03 '15 at 07:02
  • I want to remove everything in () so if it were "stuff (stuff here (more stuff) and more stuff)" I'd get stuff and nothing else. Although for future reference it would also be helpful to do the other as well although I think I could do that by using substrings. – Scoopta Jan 03 '15 at 07:04
  • multiple layers of parentheses is not a matter of regex, since the languages is not regular – gefei Jan 03 '15 at 07:05
  • Alright then what could I do about it? – Scoopta Jan 03 '15 at 07:06

2 Answers2

1

Try escaping round brackets like:

String data_message = "stuff(stuff here (more stuff) and more stuff)";
System.out.println(data_message.replaceAll("\\(.*\\)", ""));
Output:
stuff
SMA
  • 36,381
  • 8
  • 49
  • 73
  • It's as per the specification from OP. OP didn't specified about your requirement. – SMA Jan 03 '15 at 07:14
  • I didn't think that would work but it did. I thought that would have removed everything from the string. Thanks. – Scoopta Jan 03 '15 at 07:15
1

If there's no restriction on the nesting level and you're using "traditional" regexps, then the answer is, unfortunately, "no" (see, for example, the accepted answer for this question: Can regular expressions be used to match nested patterns?).

If you're ok with limited nesting or ok with making your regexp language-specific... well, check other answers to that question :)

Community
  • 1
  • 1