Tip: #188 - Search for several words at the same time
Created: December 24, 2001 9:29 Complexity: basic Author: vim_power Version: 5.7 Karma: 64/40 Imported from: Tip#188
Did you know that with VIM u can search for more
than one word with a single command.
say you want to search all occurances of "bill" or "ted", or
"harry" in a text.
in normal mode do the following.
/\(bill\)\
Comments
1) Simplified Search If you don't want to do replaces with captured text you can simplify eliminating the escaped parentheses, thus
/\(bill\)\|\(ted\)\|\(harry\) <Enter>
becomes
/bill\|ted\|harry <Enter>
Note that you do still have to escape the pipe symbol
2) Simplified Replace In the example given you don't need the escaped parens to replace the text 'bill' 'ted' or 'harry' with the word 'greg,' thus
:%s/\(bill\)\|\(ted\)\|\(harry\)/greg/g <enter>
becomes
:%s/bill\|ted\|harry/greg/g <enter>
3) Capturing the enclosed text If you do want to capture the enclosed text for replacement it's still simpler to enclose the whole statement in one set of parens, thus
/\(bill\)\|\(ted\)\|\(harry\) <Enter>
becomes
/\(bill\|ted\|harry\) <Enter>
4) The full monty Since using escaped parens -- as in \(bill\|...\) -- captures the enclosed text in a regex \1 variable you can do replacements that would otherwise be sick and wrong, like put every instance of 'bill' 'ted' or 'harry' in quotes, thus
:%s/\(bill\|ted\|harry\)/"\1"/g
Note: These tricks may work in other versions of vi as well (for instance it works in vile). I never realized you had to escape the pipe to do the 'or' trick before and assumed regexes just weren't fully implemented.
davidi--AT--msn.com , December 28, 2001 15:36
There are a few other editors that can do the trick. Like TextPad for windows, or Emacs or ..... . Any editor that uses Regular expressions.
sitar--AT--procaut.txt , January 14, 2002 5:34
If you are using the entire matched text as part of your replace pattern, it is easier to use & instead of enclosing the entire search pattern in \( ...\) and referencing it as \1. Using this, the following substitute command:
- %s/\(bill\|ted\|harry\)/"\1"/g
can be simplified to this:
- %s/bill\|ted\|harry/"&"/g
The & will be replaced with the entire matching text.
duvell--AT--beer.com , January 25, 2002 21:30
Ok, that is cool but in Emacs I heard you can have a different highlighting color for each of the matched regexp (not using this regexp syntax obviously). That would be cool to highlight a RE in one color then leave it around while you do most of your normal search highlighting using another color.
Is this possible in vim?
eagsalazar--AT--hotmail.com , November 25, 2003 16:40
Yes, have a look at [/scripts/script.php?script_id=634 vimscript #634]
ipkiss--AT--via.ecp.fr , August 11, 2004 15:03