Regular expression basics
A regular expression describes a pattern of text instead of a fixed string. The most useful pieces are:
- . any character, \d a digit, \w a letter, digit or underscore, \s whitespace
- + one or more, * zero or more, ? optional, {3} exactly three
- [abc] one of these characters, [^abc] anything else
- ^ start of line, $ end of line
- ( ) a group you can reuse, | or
Using groups in the replacement
Brackets capture part of a match. In the replacement, $1 is the first group, $2 the second, and $& is the whole match. Named groups work too, written as $<name>. To turn Smith, John into John Smith, find (\w+), (\w+) and replace with $2 $1.
Flags
- g replaces every match, not just the first.
- i ignores case.
- m makes ^ and $ match at each line.
- s lets the dot match line breaks.
- u turns on full Unicode support.
Common patterns
The list above the pattern box fills in ready-made examples: collapse extra spaces, trim line endings, remove blank lines, swap names, reformat dates, strip HTML tags and mask email addresses. Use them as starting points.
Stay safe
Test on a small sample first. Very complicated patterns on long text can run slowly, and a greedy pattern can match more than you intended. The match list shows exactly what was found.
For plain text, use find and replace. For many literal rules, see find and replace multiple. The guide compares the approaches.