Title here
Summary here
Regular expressions (regex) are a powerful tool for searching and manipulating text. In Vim, regex can enhance your ability to perform complex searches and precision text replacements, essential for editing large files or programming.
vim
..
(matches any single character), *
(zero or more of the preceding character), and +
(one or more of the preceding character).Character Classes:
[abc]
: Matches any single character a, b, or c.[^abc]
: Matches any single character except a, b, or c.[a-z]
: Matches any lowercase letter.Quantifiers:
a*
: Matches zero or more ‘a’s.a+
: Matches one or more ‘a’s.a?
: Matches zero or one ‘a’.Positional Assertions:
^
: Matches the start of a line.$
: Matches the end of a line.\b
: Matches a word boundary.Groups and Ranges:
(abc)
: Matches the exact sequence “abc”.(abc|def)
: Matches “abc” or “def”.\
to escape special characters to treat them as literals, e.g., \.
.(?:pattern)
for groups that should not be captured for backreferences.\1
, \2
, etc., to refer to the first, second, etc., captured groups during replacements.:%s/old/new/g
Replace ‘old’ with ’new’ throughout the file.
:%s/\(love\)able/\1rs/g
Convert words from “loveable” to “lovers”, demonstrating backreference usage.
:%s/old/new/gi
Perform a case-insensitive replacement.
:%s/foo\|bar/replacement/g
replaces occurrences of “foo” or “bar” with “replacement”.[:digit:]
, [:alpha:]
, and [:alnum:]
within [ ]
can match digits, alphabetic characters, and alphanumeric characters respectively.\{-}
for lazy matching.\@=
for lookahead and \@<=
for lookbehind.