Klnh13 Klnh13 - 6 months ago 3x
Javascript Question

Regular expression to select all whitespace that IS in quotes?

For example:

string text = 'some text "and some more" and some other "this is a second group" okay the end';

I'd like to capture all the spaces that are between quotation marks. The end goal is to replace those spaces with commas.

The end goal, for example:

'some text "and,some,more" and some other "this,is,a,second,group" okay the end'

For example, this would do what I'd like in javascript:

text.replace(/(["]).*?\1/gm, function ($0) {
return $0.replace(/\s/g, ',');

Unfortunately, the only tool I have available is the find/replace feature of textmate.

I've found another that does the opposite of what I need, but uses one line like I need:

text.replace(/\s+(?=([^"]*"[^"]*")*[^"]*$)/gm, ',');



You can use


See the regex demo

The \s+ matches 1 or more whitespace that is followed by an odd number of double quotes.

Details: The whitespace matching part is simple, the positive lookahead requires

  • (?:(?:[^"]*"){2})* - zero or more sequences of 2 sequences matching 0+ characters other than a " and then a " (0+ "..."s)
  • [^"]*"[^"]* - 0+ characters other than a " followed with a " and again followed with 0+ characters other than a " (an odd quote must be to the right of the currently matched whitespace)
  • $ - end of string.