6.4. Pattern-Matching Examples
Unless you are already familiar with regular expressions,
the discussion of special characters above probably looks forbiddingly
complex. A few more examples should make things clearer.
In the examples that follow, a square
(
) is used to mark a space; it is not a special character.
Let's work through how you might use some special characters in a replacement. Suppose that you have a long file and that you want to substitute the word child with the word children throughout that file. You first save the edited buffer with :w, then try the global replacement:
:%s/child/children/g
When you continue editing, you notice occurrences of words such as childrenish. You have unintentionally matched the word childish. Returning to the last saved buffer with :e!, you now try:
:%s/child/children/g
(Note that there is a space after child.) But this command misses the occurrences child., child,, child: and so on. After some thought, you remember that brackets allow you to specify one character from among a list, so you realize a solution:
:%s/child[,.;:!?]/children[ ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access