6

Folks, I'm writing a syntax highlighting script for vim, but I'm struggling on how to highlight only a submatch of a pattern.

For example, suppose that I want to highlight any number within #, like #42# to highlight only the 42 and not the #.

I don't fully understand what the \@= operator does, but I'm trying to use it like so:

syn match Number "\(#\)\@=\d\+\(#\)\@="

Edit: Just complementing Kent's answer, from the man page:

                            */\zs*
\zs Matches at any position, and sets the start of the match there: The
    next char is the first char of the whole match. |/zero-width|
    Example: >
        /^\s*\zsif
<   matches an "if" at the start of a line, ignoring white space.
    Can be used multiple times, the last one encountered in a matching
    branch is used.  Example: >
        /\(.\{-}\zsFab\)\{3}
<   Finds the third occurrence of "Fab".
    {not in Vi} {not available when compiled without the |+syntax| feature}
                            */\ze*
\ze Matches at any position, and sets the end of the match there: The
    previous char is the last char of the whole match. |/zero-width|
    Can be used multiple times, the last one encountered in a matching
    branch is used.
    Example: "end\ze\(if\|for\)" matches the "end" in "endif" and
    "endfor".
    {not in Vi} {not available when compiled without the |+syntax| feature}
6

You can use \zs and \ze:

syn match Number "#\zs\d\+\ze#"
  • In my original problem I have to match more than a single number in the same line, and I just found out that "#\zs\d\+\ze#\zs\d\+\ze#" won't work. Do you know how to make multiple matches in the same line, or I should make another question? – Kira Nov 11 '15 at 15:47
  • 1
    Are all the matches part of the same match? (I.e. between the same set of # separators?) If yes, what separates the numbers? Rewrite the rule taking into account the possible sub-separators. If not, things should already work as is. – VanLaser Nov 11 '15 at 16:00
  • I realized that my doubt is a whole new question, so I made one here. – Kira Nov 11 '15 at 16:22
  • @Kira Vanlaser is right. keep in mind that #123#456# is #123# and #456# so the same cmd should work too. – Kent Nov 11 '15 at 16:23
  • The problem is that this is not my actual problem, I've used a fictional example just for simplicity, check this question for something more specific. – Kira Nov 11 '15 at 16:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.