Regex to pick characters outside of pair of quotes

前端 未结 6 1457
广开言路
广开言路 2020-11-22 00:29

I would like to find a regex that will pick out all commas that fall outside quote sets.

For example:

\'foo\' => \'bar\',
\'foofoo\' => \'bar,         


        
6条回答
  •  死守一世寂寞
    2020-11-22 01:20

    The below regexes would match all the comma's which are present outside the double quotes,

    ,(?=(?:[^"]*"[^"]*")*[^"]*$)
    

    DEMO

    OR(PCRE only)

    "[^"]*"(*SKIP)(*F)|,
    

    "[^"]*" matches all the double quoted block. That is, in this buz,"bar,foo" input, this regex would match "bar,foo" only. Now the following (*SKIP)(*F) makes the match to fail. Then it moves on to the pattern which was next to | symbol and tries to match characters from the remaining string. That is, in our output , next to pattern | will match only the comma which was just after to buz . Note that this won't match the comma which was present inside double quotes, because we already make the double quoted part to skip.

    DEMO


    The below regex would match all the comma's which are present inside the double quotes,

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

    DEMO

提交回复
热议问题