Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim regex for matching strings

Tags:

regex

vim

How can I create a regex for Vim that accommodates for matching multiple double quotes strings on one line, without matching the text in between the two double quotes strings? A restriction on the pattern is that the double quoted strings can't contain a single quote. So far I came up with /"\([^']\{-}\)"/ to match the strings below. But as you see it will match the text in between the strings for the second line. I can't rely on white space surrounding the strings, as you see in the third line. And of course it needs to work with the fourth line as well.

  • "cat" is called "foo"
  • "cat's" name is "foo"
  • x="cat's food"
  • x = "cat"
like image 905
kodnin Avatar asked Oct 21 '22 08:10

kodnin


1 Answers

basically I want to retrieve the contents from within the double quotes. This way I can replace them with single quotes. It goes without saying that I do not want to replace double quotes for single quotes when there is a single quote inside

I didn't find a way to write a simple regex to match your need, but with vim's :s there is a way:

%s/\v"([^"]*)"/\=stridx(submatch(1),"'")>=0?submatch(0):"'".submatch(1)."'"/g

after you executed the above line, your example text would be changed into:

'cat' is called 'foo'
"cat's" name is 'foo'
x="cat's food"
x = 'cat'
like image 126
Kent Avatar answered Oct 28 '22 19:10

Kent