Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Regex to pick characters outside of pair of quotes

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

For example:

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

This would pick out the single comma on line 1, after 'bar',

I don't really care about single vs double quotes.

Has anyone got any thoughts? I feel like this should be possible with readaheads, but my regex fu is too weak.

Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...