Search code examples
regexvimvim-syntax-highlighting

Vim Regex: Capture *first* instance of word between characters


My organization has an in-house language, with syntax like:

cmo/create/mo1///tri
createpts/brick/xyz/2,2,2/0.,0.,0./1.,1.,1./1,1,1

I am writing a Vim syntax file, and would like to capture the first instance of a word enclosed by two characters (in this case, /), without capturing the characters themselves.

I.e., the regex would capture, from the lines above,

create
brick

My solution so far is to use this pattern:

[,/=" "].\{-}[,/=" "]

But from /this/and/this/and/this, it will capture /this/and/this/and/this/.

As you can see, the issue is two-fold: (i) my current solution is greedy, and (ii) captures the / characters as well, when I just want the words enclosed by these.

Thanks!


Solution

  • One possible solution:

    ^[^\/]\+\/\zs[^\/]\+\ze\/
    
    • ^ anchor the search to the BOL,
    • [^\/]\+ one or more non-slash characters, as many as possible,
    • \/ a slash,
    • \zs start the match here,
    • [^\/]\+ one or more non-slash characters, as many as possible.