Klnh13
Klnh13

Reputation: 103

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, ',');

Thanks!

Upvotes: 10

Views: 6736

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

You can use

\s+(?=(?:(?:[^"]*"){2})*[^"]*"[^"]*$)

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.

Upvotes: 13

Related Questions