|
Vim regular expressions
|
In this section we explain how to search for (and change) strings using pattern matching with regular expressions.
a) In normal mode, type
/<string> <ENTER>
for example, /hello <ENTER>.
Then each time you type n the cursor will be
relocated to the next instance of the string "hello".
b) To search for either of {"abc","aBc"}
one can type a single command:
/a[bB]c <ENTER>
where the square brackets mean "or".
c) One can search for any string in the set
{"ac", "abc", "abbc", "abbbc", ... }
using the command
/ab*c <ENTER>
where b* means "zero or more b's".
d) In order to search for a word rather
than a string. For example, to search for the word
"and" using
/and <ENTER>
will also find words containing "and" such as "sandy".
To ensure that you only find "and" add word boundaries
to the search:
/\<and\>
(Note - in this case < and > were literals, rather
than defining an action as with <ENTER>)
Subsituting a string is very like a search. For example,
changing every occurrence in a file of "abc" to "ABC" simply
requires the command:
:%s/abc/ABC/g <ENTER>
By way of explanation:
a) : means "change to command mode"
b) %s means "substitute on every line in the file"
c) /g means "replace all occurrences in the line - not just the first."
The first in this list is a well written article covering quite a lot without too much pain - well worth a read!