Find and Replace With Regex, Explained for Everyone
Find and replace can do far more than swap one word for another. This guide takes you from case and whole-word options to regular expressions, with ten recipes you can use today.

Key takeaways
- Case sensitivity and whole-word matching solve most find-and-replace surprises before you need anything fancier.
- A regular expression is a pattern: character classes say what, quantifiers say how many, and groups let you keep pieces.
- Capture groups with $1, $2 in the replacement let you reorder dates, reformat phone numbers and fix names in one pass.
- Always test a pattern on a sample and watch the match count before running it on the real document.
- The dot, greedy quantifiers and forgotten word boundaries cause almost every regex mistake beginners make.
Find and replace becomes a genuinely powerful editing tool once you understand three settings and one idea. The settings are case matching, whole-word matching and multi-line mode. The idea is the regular expression, a pattern language that describes the shape of the text you want rather than its exact letters. With it you can reformat every phone number in a document, swap the order of every date, or delete every trailing space, in a single operation.
Start with the options you already have
Most people press Ctrl+H, type a word, type its replacement and click Replace All. That works until it does not. Three options control what "match" means, and they are worth understanding before touching patterns.
Match case
By default most editors ignore capitalisation, so replacing "march" with "walk" also turns "March" into "walk" and quietly damages a date. Switch on match case whenever the word you are changing is also a name, a month, or the start of a sentence. The Find and Replace Text tool has a case-sensitive toggle for exactly this reason.
Whole words only
Replacing "cat" with "dog" without this option also changes "category" to "dogegory" and "concatenate" to "condogenate". Whole-word matching only accepts a hit when the text on either side is not a letter or digit. In regular-expression terms it wraps your search in word boundaries, which we will meet shortly.
Multi-line and dot-all
These matter once you use patterns. Multi-line mode makes the start and end anchors apply to each line rather than the whole document. Dot-all lets the dot match a line break. Leave both off until a recipe below asks for one.
What a regular expression actually is
A regular expression, usually shortened to regex, is a description of text. Instead of saying "find 2024-03-15", a regex says "find four digits, a hyphen, two digits, a hyphen, two digits". Written out, that pattern is \d{4}-\d{2}-\d{2}. Every date in that format now matches, whatever its value.
Patterns are built from a small set of parts. Ordinary letters and digits match themselves. A handful of punctuation marks have special meanings, and that is where the learning curve lives. The table below covers the parts used in the rest of this guide.
| Piece | Meaning | Example | Matches |
|---|---|---|---|
. | Any single character except a line break | c.t | cat, cot, c9t |
\d | One digit, 0 to 9 | \d\d | 42, 07 |
\w | One word character: letter, digit or underscore | \w+ | hello, item_2 |
\s | One whitespace character: space, tab or line break | a\sb | a b |
[abc] | Any one of the listed characters | gr[ae]y | grey, gray |
[^abc] | Any one character not listed | [^0-9] | any non-digit |
* | Zero or more of the previous piece | ab* | a, ab, abbb |
+ | One or more | \d+ | 7, 2024 |
? | Zero or one (optional) | colou?r | color, colour |
{n,m} | Between n and m repeats | \d{2,4} | 12, 2024 |
^ and $ | Start and end of the line (in multi-line mode) | ^Chapter | lines beginning with Chapter |
\b | Word boundary, the edge of a word | \bcat\b | cat, but not category |
( ) | Group: capture a piece for reuse | (\d+)-(\d+) | captures both numbers |
| | Either the left or the right | Mr|Mrs|Ms | any of the three titles |
\ | Escape: treat the next symbol literally | \. | a real full stop |

Character classes: what to match
A character class answers the question "which characters are allowed here?". The shorthand classes \d, \w and \s cover the common cases. Square brackets let you build your own: [A-Z] is any capital letter, [0-9a-f] is any hexadecimal digit, and [.,;:] is any one of four punctuation marks.
Inside square brackets most special characters lose their powers, so [.] is a literal full stop. The exceptions are the hyphen, which makes a range, and the caret at the very start, which negates the class. [^\s] therefore means "anything that is not whitespace".
Quantifiers: how many to match
A quantifier follows a piece and says how many times it may repeat. \d+ is one or more digits; \d* is zero or more, which also matches nothing at all; \d? is an optional single digit; \d{3} is exactly three. Quantifiers are greedy: they grab as much as they can while still letting the whole pattern succeed. That is usually what you want, but it is the source of the most famous regex mistake, covered in the mistakes section below. Adding a question mark after a quantifier, as in .*?, makes it lazy, so it grabs as little as possible instead.

Groups and backreferences: keeping the pieces
Parentheses do two jobs. They group a sequence so a quantifier applies to the whole thing, as in (ab)+, and they capture whatever matched inside them. Captured text is numbered from the left: the first opening bracket is group 1, the second is group 2, and so on.
In the replacement box you refer to a captured group as $1, $2 and so on (some editors, including Notepad++ and Vim, use \1 instead). This is what turns find and replace into a reformatting tool. Searching for (\w+) (\w+) and replacing with $2 $1 swaps every pair of words. Within the search pattern itself, \1 means "the same text that group 1 just matched", which is how you catch repeated words.
Search: (\d{2})/(\d{2})/(\d{4}) Replace: $3-$2-$1
Input: Paid on 15/03/2024 and 02/11/2024
Output: Paid on 2024-03-15 and 2024-11-02
Before running any recipe with groups on a real document, paste a few sample lines into the Regex Tester. It highlights every match and shows what each group captured, so a wrong bracket is obvious before it does any damage.
Ten practical recipes
Each recipe gives the search pattern, the replacement, and the setting to switch on. The $1 style is used throughout; swap to \1 if your editor needs it.
- Remove trailing spaces and tabs. Search
[ \t]+$, replace with nothing, multi-line on. Fixes the invisible clutter that makes diffs noisy and CSV imports fail. - Collapse runs of spaces to one. Search
{2,}(a space followed by the quantifier), replace with a single space. Common after copying from a PDF. - Delete duplicated words. Search
\b(\w+)\s+\1\b, replace with$1, case-insensitive on. Turns "the the report" into "the report". Run it twice if a word appears three times in a row. - Reformat phone numbers. Search
\(?(\d{3})\)?[-. ]?(\d{3})[-. ]?(\d{4}), replace with$1-$2-$3. Takes "(555) 123 4567", "555.123.4567" and "5551234567" and produces "555-123-4567". Adjust the group lengths to your country's format. - Convert DD/MM/YYYY dates to ISO. Search
\b(\d{2})/(\d{2})/(\d{4})\b, replace with$3-$2-$1. ISO dates sort correctly in spreadsheets and file names. - Collapse multiple blank lines to one. Search
\n\s*\n, replace with\n\n. If your tool does not understand\nin the replacement box, use a tool that does, or paste in a real line break. - Swap "Surname, First" to "First Surname". Search
^(\w[\w' -]*), *(\w[\w -]*)$, replace with$2 $1, multi-line on. Handles names such as O'Brien and double-barrelled surnames. - Strip HTML tags. Search
<[^>]+>, replace with nothing. The negated class[^>]stops the match at the first closing bracket, which is why this does not swallow whole paragraphs. - Remove leading list numbers. Search
^\d+[.)]\s+, replace with nothing, multi-line on. Turns "3. Buy milk" into "Buy milk" so you can re-number or convert to bullets. - Add a currency symbol to bare prices. Search
\b(\d+\.\d{2})\b, replace with£$1. The escaped dot is essential;\d+.\d{2}would also match "2024x15".
Chaining recipes on a real file
Recipes are most useful in sequence. Suppose a colleague sends a contact list exported from an old system: names written as "Surname, First", phone numbers in three different styles, double spaces everywhere and a blank line after every entry. Run recipe 2 first to normalise the spacing, because the later patterns assume single spaces. Run recipe 6 to close the blank lines. Then run recipe 4 on the phone numbers and recipe 7 on the names. Four passes, each checked in the tester, and a list that took an afternoon to tidy by hand is clean in a couple of minutes.
The order matters more than it looks. If you fixed the names before the spacing, the name pattern would fail on entries with two spaces after the comma, and you would not notice until the file was half done. As a rule, clean whitespace first, structure second, and formatting last.
For removing repeated lines rather than repeated words, you do not need a pattern at all. The Duplicate Line Remover keeps the first copy of each line and optionally ignores case and surrounding spaces.
Common mistakes and how to avoid them
Forgetting that the dot means anything
Searching for 3.14 also matches "3514" and "3-14". When you mean a real full stop, write \.. The same applies to +, ?, (, [ and $: escape them when you want the literal character.
Greedy matching
The pattern ".*" on the line say "hello" and "goodbye" matches from the first quote to the last one, swallowing the word "and". Use the lazy form ".*?" or, better, a negated class such as "[^"]*", which cannot cross a quote.
Missing word boundaries
A search for is matches inside "this", "island" and "crisis". Wrap it as \bis\b or switch on whole-word matching.
Wrong mode for anchors
If ^ and $ only match once in a whole document, multi-line mode is off. Turn it on and they match at every line.
Mixing up $1 and \1
If your replacement comes out as the literal text "$1", the editor wants \1, or the other way round. Check the tool's help once and remember the answer.
Not testing first
Replace All is instant and sometimes irreversible. Work on a copy, use Find Next to inspect the first few matches, and compare the match count with what you expect. If a pattern that should match 40 phone numbers reports 400 matches, it is matching something you did not intend.
Regular expressions are not the right tool for parsing full HTML, JSON or code. They work well on predictable, line-oriented text; for nested structures use a proper formatter or parser instead.
Where to go next
Build and check a pattern in the Regex Tester, then run it on the real document with the Find and Replace Text tool, which supports regular expressions, case matching and whole-word mode. Both run entirely in your browser, so the text never leaves your machine.
Frequently asked questions
What does $1 mean in find and replace?
In the replacement box, $1 stands for whatever the first pair of brackets in your search pattern captured, $2 for the second pair, and so on. Searching for (\d{2})/(\d{4}) and replacing with $2-$1 turns 03/2024 into 2024-03. Some editors, including Notepad++ and Vim, write the same thing as \1 and \2, so check which style your tool expects if the output shows the literal characters.
How do I find and replace whole words only?
Switch on the whole-word option if your editor has one. In a regular expression, wrap the word in \b markers, which match the boundary between a word character and anything else: \bcat\b finds cat but not category or concatenate. The boundary itself has no width, so the replacement does not need to include it; the surrounding text stays untouched.
Is find and replace case sensitive?
Usually not by default. Most editors and online tools treat "March" and "march" as the same word until you turn on match case or case-sensitive mode. That default is convenient for prose but dangerous when the word is also a name, a month or an abbreviation. If a replacement has changed text it should not have touched, case matching is the first setting to check.
How do I remove duplicate words with regex?
Search for \b(\w+)\s+\1\b and replace with $1. The brackets capture a word, \s+ allows any spacing, and \1 insists that the same word follows. Turn on case-insensitive matching so "The the" is caught as well. Run the replacement a second time if any word appeared three times in a row, because each pass removes one copy per position.
Can regex match across multiple lines?
Yes, with the right mode. By default the dot does not match a line break, so a pattern cannot span lines; dot-all mode changes that. Separately, multi-line mode makes the ^ and $ anchors apply to each line rather than the whole text. For recipes that collapse blank lines you can also match the line break directly with \n, which works in either mode.
Does regex find and replace work on large documents?
In a browser-based tool it works comfortably on documents of a few megabytes, which is many thousands of pages of text. The practical limit is the pattern, not the size: a pattern with nested quantifiers such as (a+)+ can take exponentially long on some inputs. Keep patterns simple, prefer negated character classes over .* and test on a sample before running on the full file.
Try the tools from this guide
Related guides
Invisible Characters Explained: Zero-Width Spaces and Friends
Unicode has a handful of characters that take up no space on screen. Here is what each one is for, where it causes trouble, and how to find and remove it.
Read the guideHow to Clean Up Text Pasted from PDFs, Emails and Web Pages
Text copied from a PDF, an email or a web page comes with broken lines, stray spaces and hidden characters. This workflow fixes each problem in turn, in a few minutes, with no retyping.
Read the guideBold and Italic Text on Social Media: How It Works and When to Avoid It
The bold and italic text in bios and posts is not real formatting. It is a set of Unicode symbols borrowed from maths. Learn how it works, where it breaks and when to skip it.
Read the guide

