-1

With a string like so:

3 SOME STRING (remove me) 6 SOME OTHER STRING (also remove me!) 8 THIRD STRING (and me)

with the goal to strip away anything in parentheses and having the string turned into:

3 SOME STRING 6 SOME OTHER STRING 8 THIRD STRING 

My best effort so far has been:

private String removeAnythingInParentheses(String input) {
    return Pattern.compile("\\(.*\\)").matcher(input).replaceAll("").trim();
}

This however replaces too much of my string and leaves me with (I guess it matches the first parentheses to the very last in the string):

3 SOME STRING

I am sure there are some nifty features of Pattern and Matcher that I could use but I cannot figure them out...

saidaspen
  • 560
  • 1
  • 5
  • 13
  • I have looked at these two posts, but still cannot seem to figure it out: https://stackoverflow.com/questions/34180794/how-to-replace-multiple-matched-regex and https://stackoverflow.com/questions/27415584/replace-multiple-capture-groups-using-regexp-with-java – saidaspen Aug 18 '17 at 05:46
  • 2
    Use something like: `"\\([^\\(\\)]*\\)"` – Maurice Perry Aug 18 '17 at 05:48
  • Add a `?` after the `*`. – shmosel Aug 18 '17 at 05:49
  • Maurice Perry: Nice one worked like a charm! Had two redundant escapes within the [ ] which could be removed! – saidaspen Aug 18 '17 at 05:52

2 Answers2

1

As suggested by comment. The correct answer was:

private String removeAnythingInParentheses(String input) {
    return Pattern.compile("\\([^()]*\\)").matcher(input).replaceAll("").trim();
}
saidaspen
  • 560
  • 1
  • 5
  • 13
1

I guess a simple use of String.replaceAll with a modified regex would be easier on the eyes

 input.replaceAll("\\(.*?\\)", "");

full code

    String input = "3 SOME STRING (remove me) 6 SOME OTHER STRING (also remove me!) 8 THIRD STRING (and me)";
    input = input.replaceAll("\\(.*?\\)", "");

    System.out.println(input);

output

3 SOME STRING 6 SOME OTHER STRING 8 THIRD STRING

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64