Vime regex to replace spaces inside quotes

I have text in the following format:

ERR_OUT_OF_MEM, "ERR OUT OF MEM" ERR_SOMETHING_BAD, "ERR SOMETHING BAD" 

I want to replace all spaces in the text that are in quotation marks with underscores:

  ERR_OUT_OF_MEM, "ERR_OUT_OF_MEM" ERR_SOMETHING_BAD, "ERR_SOMETHING_BAD" 

The best regular expression I could find is this:

 \("\w\+\)\@<= 

(there is a place at the end of it)

but it only finds the first space in each row, and I will need to repeat this several times to get the desired effect.

Any way to do it in one shot?

Thanks!

+7
vim regex
source share
3 answers

There is, of course, a pattern of length 0 that works in one pass, but since I have never had much success in using, I prefer this approach:

 :%s/\%("[^"]*"\)*\("[^"]*"\)/\=substitute(submatch(1), ' ', '_', 'g')/g 

Note: double quotes are kept grouped 2 by 2 so as not to convert

 foo bar "foo bar" "foo barr" 

in

 foo bar "foo_bar"_"foo_barr" 

EDIT: as indicated in the ramp, more than enough:

 %s/"[^"]*"/\=substitute(submatch(0), ' ', '_', 'g')/g 
+6
source share

This is not a universal solution, since it will correspond to any space that appears somewhere after a double quote in a string, but it should work for strings in the specified format:

 s/\v(\".*)@<= /_/g 

I used the \ v (verymagic) token because I think this makes the regex a bit more readable, and I included the entire substitution command, since the “g” at the end is important.

For those at home, this regular expression first sets up a "very small" mode with \ v. Then it defines a token (\".*) , Which roughly means" double quote, and then something else "and uses the lookbehind @<= statement to say:" match only those that match the last token "- in other words, only match what comes somewhere after the double quote, finally there is a space that actually matches, and the wildcard term is the underscore that we want to replace, and g says “substitute all matching terms,” so we’re not just we get found the first match .

+6
source share

My PatternsOnText provides the command :SubstituteInSearch . With it, you first search for quoted strings, then do :substitute only within matches:

 /".\{-}" :SubstituteInSearch/_/ /g 
0
source share

All Articles