简体   繁体   中英

Javascript regEx to remove all parentheses except between special characters

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM