poby
poby

Reputation: 1746

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:

No highlight should appear in the following:

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

Upvotes: 1

Views: 295

Answers (2)

poby
poby

Reputation: 1746

@ryuichiro gave me what I needed to find the answer so I've credited him for it. But the full solution which allows for unlimited number of keywords is as follows:

syn match ngzRewLine /\w\+\ze\(;\|\s.\{-};\)/ contains=ngzRew contained
syn keyword ngzRew house contained
syn keyword ngzRew cheesecake contained
syn keyword ngzRew ...etc contained

Upvotes: 1

ryuichiro
ryuichiro

Reputation: 3875

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.

Upvotes: 1

Related Questions