Regular expressions explained
Short answer
A regular expression (regex) is a small pattern language for matching text. You describe what the text should look like using characters, special symbols, and repetition rules, and the engine finds or replaces every match.
The building blocks
Most of a regex is literal characters that match themselves. The power comes from a handful of special pieces that describe sets of characters, how often they repeat, and where they sit.
.matches any single character except a newline\dmatches a digit,\wa word character,\swhitespace[abc]matches one of a, b, or c;[a-z]matches a range*zero or more,+one or more,?zero or one{2,4}matches between two and four repetitions^anchors to the start,$to the end of the line
^[\w.+-]+@[\w-]+\.[a-z]{2,}$Groups and alternation
Parentheses ( ) create a group you can repeat or capture, and the pipe | means 'or'. So (cat|dog)s? matches cat, cats, dog, or dogs. Captured groups let you pull pieces out of a match or reuse them in a replacement.
. * + ? ( ) [ ] { } ^ $ | \ have special meaning. To match one literally, put a backslash in front of it, for example \. to match a real dot.Common mistakes
- Forgetting that
.matches almost anything, which makes patterns too greedy. - Not anchoring with
^and$when you need to match the whole string. - Trying to parse HTML or deeply nested formats with regex, which it is not built for.