Search code examples
regexvimvim-syntax-highlighting

how to make vim syn regex to capture word with trailing space?


I'm trying to make a vim regex to highlight word house in this example but only if followed by whitespace and only if sentence ends in semicolon.

herbert house mouse; bear care; house moose hat; // both instances of house highlighted
cow (house) banana goat; car bar; //house must NOT be highlighted
house beagle //house must NOT be highlighted

From my VIM syntax file:

syn match ngzRewLine '\w\+[^;]\{-};' contains=ngzRew
syn keyword ngzRew house contained

This works great except (house) is being highlighted. What regex can I use that will only match words with trailing whitespace and a non greedy ending semicolon?

EDIT

To summarise, words in the ngzRew keyword group should be highlighted in the following cases:

  • house mouse;
  • cat house mouse;
  • house banana;catfish house shoes;
  • house;

No highlight should appear in the following:

  • house
  • cat (house) cheese;

house is used here as an example but there are other keywords in the ngzRew keyword group and the behavior should be the same.


Solution

  • You could do it this way (this is probably not very convenient but I can't think of a better way because of the following whitespace)

    highlight MyGroup ctermbg=green guibg=green
    syntax match MyGroup /\(house\|car\)\ze\(;\|\s.\{-};\)/
    

    Now it matches a car as well.

    • \ze matches at any position, and sets the end of the match there,
    • \s whitespace character,
    • . matches any single character,
    • \{-} matches 0 or more of the preceding atom, as few as possible,
    • \(\) braces can be used to make a pattern into an atom,
    • \| is "or" operator in a pattern.