0

Sometimes I just want to see whether a regex is matching the right stuff. If I could cause Vim to visually select the matching text, it would be one way to do this. Is there a method for doing this?

1
  • 4
    Have you tried eg incsearch
    – D. Ben Knoble
    Jan 14, 2018 at 11:55

3 Answers 3

5

Vim will use a colour for search matches if you have the 'hlsearch' option switched on:

:set hlsearch

You can then just search for your regular expression and see if it is highlighted:

/regex

Note that, if you also have 'incsearch' set, Vim will begin highlighting matches as soon as you start typing in your regular expression: with that option disabled the highlighting won't occur until you execute the search by pressing Enter.

The Search highlighting group is used for highlighting. You can check how this group is configured with the command:

:highlight Search

When you are done, you can remove the highlighting with the command:

:nohlsearch

Note the difference between this and :set nohlsearch, which turns off search highlighting entirely: the :nohlsearch command leaves the hlsearch option on, and will only turn off highlighting until the next time you search.

See :help 'hlsearch' for more details.

2
  • 2
    for visually selecting a regex, the gn command has been added Jan 15, 2018 at 17:17
  • 1
    @ChristianBrabandt As far as I can tell from the question and later comment, by "visually select" the OP means "highlight", rather than "make a visual-mode selection". (The OP has already rejected an answer suggesting gn, and I don't understand what is meant by the first sentence of the question if the OP really means "make a visual-mode selection").
    – Rich
    Jan 15, 2018 at 17:36
4

This can be achieved with gn.

See :h gn for details.

2
  • I know how to not match. The problem is how to activate the visual selection. Jan 14, 2018 at 5:39
  • 2
    Not sure what you mean. gn activates the visual selection here (for the next match)
    – Naumann
    Jan 14, 2018 at 6:16
0

You can use :g/<pattern>/y to yank matches or :v/<pattern>/y to yank on no match, I believe.

2
  • 2
    Beware that this will run the :yank command once for each line that matches, so you will only have the last matching line in the register (unless you specify an uppercase letter like :global/…/yank A).
    – D. Ben Knoble
    Mar 3, 2022 at 15:15
  • 1
    Also that doesn't really answer the question: OP wanted to visually check their regex, your command would just yank a line (lines with Ben's fix) without visual feedback.
    – statox
    Mar 3, 2022 at 16:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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