How to extract regex matches using Vim

后端 未结 5 1776
悲哀的现实
悲哀的现实 2020-12-08 15:52

An example:

case Foo:
    ...
    break;
case Bar:
    ...
    break;
case More: case Complex:
    ...
    break:
...

I’d like to retrieve al

5条回答
  •  误落风尘
    2020-12-08 16:34

    How to use vim regex to extract the word from the following line, given that 'help' might be any word like 'rust' or 'perlang'.

    vim:tw=78:ts=8:ft=help:norl:
    

    Solution:

    let foo = substitute(foo, '^\s*vim:.*:ft=\([a-z]\+\).*:\s*$', '\1', '')
    echo "foo: '" . foo . "'"
    

    Prints:

    foo: 'help'
    

    Guru meditation: What's going on here?

    Take the string in the variable foo and match it to assert the beginning of the line, then any number of spaces, the literal vim and a literal colon, then any number of any characters followed by colon ft= with any word with letters, then anything, and assert the line ends with a colon. Throw all that into a register named 1, then get that back in parameter 2 which substitute takes on and replaces the prior string with.

    As a general philosophy, any regex longer than your finger on the screen is an epic fail, so decrease screen resolution until it fits.

提交回复
热议问题