Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim regex with meta-characters

Tags:

regex

vim

I have the following in a text file:

This is some text for cv_1 for example
This is some text for cv_001 for example
This is some text for cv_15 for example

I am trying to use regex cv_.*?\s to match cv_1, cv_001, cv_15 in the text. I know that the regex works. However, it doesn't match anything when I try it in Vim.

Do we need to do something special in Vim?

like image 686
Omnipresent Avatar asked Oct 21 '09 03:10

Omnipresent


People also ask

Does vim support regex?

Vim's regexes are most similar to Perl's, in terms of what you can do. The difference between them is mostly just notation; If you want a better (more serious) explanation, look up "Traditional NFA" in Mastering Regular Expressions.

How to search regex in Vim?

In normal mode, press / to start a search, then type the pattern ( \<i\> ), then press Enter. If you have an example of the word you want to find on screen, you do not need to enter a search pattern. Simply move the cursor anywhere within the word, then press * to search for the next occurrence of that whole word.

How do I find special characters in Vim?

^ * $ \ ? ) have special significance to the search process and must be “escaped” when they are used in a search. To escape a special character, precede it with a backslash ( \ ). For example, to search for the string “anything?” type /anything\? and press Return.

How do you replace a word in Vim?

The simplest way to perform a search and replace in Vim editor is using the slash and dot method. We can use the slash to search for a word, and then use the dot to replace it. This will highlight the first occurrence of the word “article”, and we can press the Enter key to jump to it.


1 Answers

The non-greedy character ? doesn't work in Vim; you should use:

cv_.\{-}\s

...instead of:

cv_.*?\s

Here's a quick reference for matching:

     * (0 or more) greedy matching
    \+ (1 or more) greedy matching
  \{-} (0 or more) non-greedy matching
\{-n,} (at least n) non-greedy matching
like image 145
gak Avatar answered Oct 20 '22 22:10

gak