Search code examples
vimsubstitution

Select and substitute whole word before a special character


I have this content in my file:

{
  "performanceHighToLow" : {
    tabs     : {
      bySales : "by sales",
      byOrder : "by order"
    },
    category : "performanceHighToLow",
    onTabClick
  },
  performanceLowToHigh : {
    tabs     : {
      bySales : "by sales",
      byOrder : "by order"
    },
    category : "performanceLowToHigh",
    onTabClick
  }
}

I was wondering if I could write a regex to quote all dequoted words. On the same subject, is there a way to select full word(word boundary) before the colon(:) occurrence.


Solution

  • To match words before a colon you could match word character + possible whitespace + colon, but stopping the match after the word itself with \ze:

    /\w\+\ze\s*:
    

    To also match the possible last word in a line (line onTabClick) you could modify the previous pattern with an or at the colon / EOL:

    /\w\+\ze\s*\(:\|$\)
    

    In which case it could be easier to enable very-magic to simplify escaping:

    /\v\w+\ze\s*(:|$)
    

    To then "quote" these results:

    :%s/\v\w+\ze\s*(:|$)/"&"/g