0

I need a regex that replaces all brackets with a single bracket, but not if an apostrophe is leading the bracket

Examples

a) ))) --> expected )
b) )))))) --> expected )
c) '))) --> expected ))

Would anybody please help? I tried replaceAll("[^']\\)\\)+", ")"); but unfortunately this is not working.

Morgan
  • 755
  • 1
  • 10
  • 28

3 Answers3

3

For your example data, you could match ') and capture in a group one or more ).

Then replace with a single )

'\)|(\)+)

As per recommendation from @ctwheels (Thanks for that!) this can be shortened to:

'\)|\)+

Explanation

This will use an alternation to match either ') or multiple times )

When this matches, you can replace it with a single )

The fourth bird
  • 96,715
  • 14
  • 35
  • 52
1

Use one regex to remove extra parentheses:

replaceAll("(?<!')\\)+", ")")

And another one to get rid of the quotes ':

replaceAll("'\\)", ")")

Putting this together:

System.out.println("')'))))".replaceAll("(?<!')\\)+", ")").replaceAll("'\\)", ")"));

Prints ))).

Try it online here.

O.O.Balance
  • 2,507
  • 4
  • 20
  • 34
  • Can be condensed into one regex instead of two separate calls. I just deleted my answer that resembles this though because the fourth bird's answer is the same, but shorter and performs better. – ctwheels Mar 23 '18 at 14:51
  • @ctwheels I elected to use two calls for readability, but The fourth bird's answer's simplicity is hard to match. – O.O.Balance Mar 23 '18 at 14:53
0

Try regex:

(?<!(\'))\)+

replaceAll("(?<!(\\'))\\)+", ")");
Frido
  • 313
  • 4
  • 14