Home > Mobile >  Javascript regEx to remove all parentheses except between special characters
Javascript regEx to remove all parentheses except between special characters

Time:10-14

I need a regEx to remove all ( and ) from a string, except those between two @.

Example:

( [15] == @value 1@ || [15] == @value 2@ )  &&  ( [5] == @value 3 (ignore these)@ || [5] == @value 4@ )  ||  ( [2] == @value 5@ )

The string I need:

[15] == @value 1@ || [15] == @value 2@  &&  [5] == @value 3 (ignore these)@ || [5] == @value 4@  ||  [2] == @value 5@ 

I tried something with this non-capturing group to split with whitespaces except those between @ but could not find the way:

(?:@[^@]*@|\S)

I'm under pressure to solve this, any help is appreciated, thank you.

CodePudding user response:

You may use this regex for matching:

\s*[()](?=(?:[^@]*@[^@]*@)*[^@]*$)\s*

And replace with just empty string.

RegEx Demo

RegEx Details:

  • \s*: Match 0 or more whitespaces
  • [()]: Match ( or )
  • (?=: Start positive lookahead
    • (?:[^@]*@[^@]*@)*: Match 0 or more pairs of @...@ substrings
    • [^@]*: Match 0 more of anything but @
    • $: End
  • ): End positive lookahead
  • \s*: Match 0 or more whitespaces
  • Related