Regular expressions, usually shortened to regex, are patterns used to match text. They are useful when searching logs, filtering command output, validating text, or finding patterns inside files.
If you are learning Linux commands like grep, awk, sed or find, regex will make those tools much more powerful.
Want to test examples as you read? Use the Regex Tester on CommandLineQuiz.
A regex pattern describes text you want to match. For example:
error
This matches the word error.
A more flexible pattern might be:
error|warning|failed
This matches error, warning or failed.
You can try this pattern in the online Regex Tester.
. matches any single character.* means zero or more of the previous character or group.+ means one or more of the previous character or group.? means optional.| means OR.^ matches the start of a line.$ matches the end of a line.[0-9] matches any digit.[a-z] matches lowercase letters.\d often means digit, depending on the regex engine.For Linux log searches, regex is commonly used with grep.
grep -E "error|warning|failed" app.log
The -E option enables extended regular expressions, making patterns like | easier to use.
You can build grep commands using the Grep Command Builder, then practise with the Grep Command Quiz.
\b(?:\d{1,3}\.){3}\d{1,3}\b
[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}
\s[45]\d{2}\s
\b\d{4}-\d{2}-\d{2}\b
These are included as presets in the Regex Tester.
Regex is especially useful when investigating logs. For example, to search for common problems:
grep -Ei "error|warning|failed|fatal" /var/log/syslog
For web access logs, you might look for failed requests:
grep -E "\s[45][0-9]{2}\s" access.log
For a more complete walkthrough, read Search Logs for Errors on Linux.
grep when you need grep -E.The easiest way to learn is to test patterns, change them, and see what breaks. Regex is basically controlled chaos with punctuation.