Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match foo or bar vim regex

Tags:

regex

vim

Is there a method of matching multiple words at once in a vim search-and-replace? Something like:

:%s/foo|bar//g

to search for foo or bar and replace with nothing (this searches for the pattern foo|bar, which isn't what I want). I can search for multiple characters this way:

abcdef
:%s/[ace]//g

results in:

bdf

Can I do the same thing with words?

I'm well aware I could do this like this:

:%s/foo//g
:%s/bar//g

I'm looking for a one-line solution, if such a thing exists.

like image 970
simont Avatar asked Dec 22 '12 13:12

simont


People also ask

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.

What is '?' In Regex?

It means "Match zero or one of the group preceding this question mark." It can also be interpreted as the part preceding the question mark is optional. In above example '?' indicates that the two digits preceding it are optional. They may not occur or occur at the most once.

Does vim support Regex?

Vim has several regex modes, one of which is very magic that's very similar to traditional regex. Just put \v in the front and you won't have to escape as much.

Does Regex match anything?

Matching a Single Character Using RegexThe matched character can be an alphabet, a number or, any special character. To create more meaningful patterns, we can combine the dot character with other regular expression constructs. Matches only a single character.


2 Answers

In vim regexes, the alternation operator needs to be escaped with a backslash: use foo\|bar.

like image 97
fge Avatar answered Nov 04 '22 00:11

fge


Instead of escaping | with a backslash, you can use vim's "very magic" mode with the \v sequence:

:%s/\vfoo|bar//g
like image 43
nrz Avatar answered Nov 03 '22 22:11

nrz