Regular expressions (regex) are powerful tools used for pattern matching and text manipulation in various programming and scripting languages. They allow users to search, match, and manipulate text based on specific patterns.
Literal Characters: Matches the exact characters.
abc
matches "abc".Metacharacters: Special characters that have specific meanings in regex.
.
: Matches any single character except a newline.*
: Matches zero or more occurrences of the preceding element.+
: Matches one or more occurrences of the preceding element.?
: Matches zero or one occurrence of the preceding element.^
: Matches the start of a line.$
: Matches the end of a line.[]
: Matches any single character within the brackets.|
: OR operator, matches either the pattern before or the pattern after the |
.()
: Groups multiple tokens together and remembers the matched text.\\
: Escapes a metacharacter to be used as a literal.Literal Match
Matches the exact characters in the text.
grep "abc" file.txt
This command searches for the string "abc".
Dot (.)
Matches any single character except a newline.
grep "a.c" file.txt
This command matches "abc", "a1c", "a-c", etc.
Asterisk (*)
Matches zero or more occurrences of the preceding element.
grep "ab*c" file.txt
This command matches "ac", "abc", "abbc", "abbbc", etc.
Plus (+)
Matches one or more occurrences of the preceding element.
grep "ab+c" file.txt
This command matches "abc", "abbc", "abbbc", etc., but not "ac".
Question Mark (?)
Matches zero or one occurrence of the preceding element.
grep "ab?c" file.txt
This command matches "ac" and "abc".
Caret (^)
Matches the start of a line.
grep "^abc" file.txt
This command matches any line that starts with "abc" .
Dollar ($)
Matches the end of a line.
grep "abc$" file.txt
This command matches any line that ends with "abc".
Brackets ([])
Matches any single character within the brackets.
grep "[aeiou]" file.txt
This command matches any line containing a vowel (a, e, i, o, u).
Negation within Brackets ([^])
Matches any single character not within the brackets.
grep "[^aeiou]" file.txt
This command matches any line containing a character that is not a vowel.
OR (|)
Matches either the pattern before or the pattern after the |
.
grep "abc\\|def" file.txt
This command matches lines containing either "abc" or "def".
Grouping ()
Groups multiple tokens together and remembers the matched text.
grep "\\(abc\\)\\{2,\\}" file.txt
This command matches lines containing "abcabc" .
Escaping ()
Escapes a metacharacter to be used as a literal.
grep "a\\.c" file.txt
This command matches "a.c" in file.txt
.
Matching Word Boundaries
Use \\b
to match word boundaries.
grep "\\bword\\b" file.txt
This command matches the word "word" as a whole word.