Home / Text tools / Find and replace with regex

Regex Find and Replace

Search with a regular expression, replace with groups such as $1, and see every match with its captured groups.

Matches and groups

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.

Frequently asked questions

What does $1 mean in the replacement?

It inserts the text captured by the first group in brackets. $2 is the second group, and so on.

How do I match a literal dot or bracket?

Put a backslash before it, such as \. or \( , because those characters have special meanings.

Why does my pattern match too much?

Quantifiers are greedy by default. Add a question mark, as in .*?, to make them match as little as possible.

Which regex flavour is this?

JavaScript regular expressions, run in your browser.