Regex to pick characters outside of pair of quotes

前端 未结 6 1464
广开言路
广开言路 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条回答
  •  旧时难觅i
    2020-11-22 01:09

    This will match any string up to and including the first non-quoted ",". Is that what you are wanting?

    /^([^"]|"[^"]*")*?(,)/
    

    If you want all of them (and as a counter-example to the guy who said it wasn't possible) you could write:

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

    which will match all of them. Thus

    'test, a "comma,", bob, ",sam,",here'.gsub(/(,)(?=(?:[^"]|"[^"]*")*$)/,';')
    

    replaces all the commas not inside quotes with semicolons, and produces:

    'test; a "comma,"; bob; ",sam,";here'
    

    If you need it to work across line breaks just add the m (multiline) flag.

提交回复
热议问题