Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

javascript - Regex to match only comma's but not inside multiple parentheses

Okay, i have this case where comma are inside parenthesis, I want to match the commas that are only outside the parenthesis.

Input : color-stop(50%,rgb(0,0,0)), color-stop(51%,rgb(0,0,0)), color-stop(100%,rgb(0,0,0)))

Output(i'm looking for):color-stop(50%,rgb(0,0,0))**,** color-stop(51%,rgb(0,0,0))**,** color-stop(100%,rgb(0,0,0)))

And this is my regex:-

/(?![^(]*)),/g

The sad part is, it doesn't work when there is a multiple parenthesis :(

Regex

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is the regex which works perfectly for your input.

,(?![^()]*(?:([^()]*))?))

DEMO

Explanation:

,                        ','
(?!                     negative look ahead, to see if there is not:
  [^()]*                   any character except: '(', ')' (0 or
                           more times)
  (?:                      group, but do not capture (optional):
    (                       '('
    [^()]*                   any character except: '(', ')' (0 or
                             more times)
    )                       ')'
  )?                       end of grouping, ? after the non-capturing group makes the
                           whole non-capturing group as optional.
  )                       ')'
)                        end of look-ahead

Limitations:

This regex works based on the assumption that parentheses will not be nested at a depth greater than 2, i.e. paren within paren. It could also fail if unbalanced, escaped, or quoted parentheses occur in the input, because it relies on the assumption that each closing paren corresponds to an opening paren and vice versa.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...