This guide explains how regular expressions work, including syntax, patterns, and practical examples used in Linux, programming, and text processing. Regular expressions, often called regex, are patterns used to match, search, and manipulate text efficiently.
What Is a Regular Expression
A regular expression is a sequence of characters that defines a search pattern. It is commonly used in command-line tools, programming languages, text editors, and data validation.
Basic Components of Regular Expressions
Literal Characters
Literal characters match themselves.
cat
Matches the exact string cat.
Metacharacters
Metacharacters have special meanings in regular expressions.
- . matches any single character
- ^ matches the start of a line
- $ matches the end of a line
- * matches zero or more occurrences
Character Classes
Character classes match any one character from a set.
[abc]
Matches a, b, or c.
[a-z]
Matches any lowercase letter.
Quantifiers
Quantifiers specify how many times a character or group should appear.
- * zero or more times
- + one or more times
- ? zero or one time
- {n} exactly n times
- {n,m} between n and m times
a+
Matches one or more occurrences of a.
Anchors
Anchors match positions rather than characters.
^root
Matches lines starting with root.
bash$
Matches lines ending with bash.
Grouping and Alternation
Parentheses are used to group patterns, and the pipe symbol is used for alternation.
(cat|dog)
Matches cat or dog.
Escaping Special Characters
To match a metacharacter literally, escape it with a backslash.
\.
Matches a literal dot character.
Practical Examples
Validate an Email Address
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
Match an IP Address
([0-9]{1,3}\.){3}[0-9]{1,3}
Find Lines Containing Numbers
.*[0-9].*
Conclusion
Regular expressions provide a powerful way to search and manipulate text. Understanding how regex patterns work allows administrators and developers to automate tasks, validate input, and process data efficiently.