HSHimanshu Sharma
Free Tools

Regular expressions for beginners: patterns, flags and the Regex Tester

Advertisement

A regular expression, or regex, is a short pattern that describes a kind of text: "a phone number", "an email-like string", "every word that starts with a capital letter". With one line you can find, check or replace text that would take twenty lines of ordinary code. Regexes look like noise at first (^\d{3}-\d{4}$), but they are built from a few small pieces, and once you know those you can read and write most of them. The free Regex Tester lets you try a pattern against sample text and shows the matches highlighted and listed with their groups as you type. This guide teaches the building blocks and the mistakes that cost the most time.

How the tester works

You enter three things: the pattern, the flags and the test text. The tool then highlights every match in the text, tells you how many there are, and lists each one with its position and the contents of its capture groups. It uses the JavaScript engine of your browser, so the results are exactly what JavaScript code will produce. Other languages (PHP, Python, Java) share most of the syntax but differ in details, such as how named groups or Unicode are written. Nothing is uploaded; matching runs on your device.

If a pattern is invalid, for example because a bracket is not closed, the tool shows the error message instead of results, which is a fast way to find a typo.

The building blocks

Literal characters match themselves: the pattern cat finds cat inside concatenate.

Character classes match one character from a set:

Pattern Matches
\d a digit, 0 to 9
\w a letter, digit or underscore
\s a space, tab or line break
. almost any single character (not a line break)
[abc] a, b or c
[a-z] any lower-case letter
[^0-9] any character that is not a digit

The capital forms mean the opposite: \D is a non-digit, \W a non-word character and \S a non-space.

Quantifiers say how many times the previous item may repeat:

Pattern Meaning
+ one or more
* zero or more
? zero or one (optional)
{3} exactly 3
{2,5} 2 to 5
{3,} 3 or more

Anchors fix the position: ^ is the start, $ the end, and \b a word boundary (the edge between a word character and a non-word character).

Groups and choices: parentheses ( ) group part of a pattern and capture what it matched, | means "or", and (?: ) groups without capturing.

Put them together. The pattern colou?r matches both color and colour, because the u is optional. The pattern \d+ on a1b22c333 finds 1, 22 and 333, which are the runs of one or more digits. The pattern ^\d{3}-\d{4}$ accepts a seven-digit phone number shape such as 555-1234 and nothing else.

Capture groups

Parentheses do two jobs: they group and they remember. The default example in the tool is (\w+)@(\w+)\.com, run against Write to ada@example.com or grace@example.com today.. It finds two matches. For the first, group 1 is ada and group 2 is example; for the second, group 1 is grace and group 2 is example. The list under the highlighted text shows the match, its position and each group, so you can see exactly which part of the pattern caught which part of the text.

Groups are what make regexes useful for extraction and replacement: capture the pieces, then rearrange them. You can also name a group, as in (?<year>\d{4})-(?<month>\d{2}), which gives year and month instead of numbers. Named groups are supported by current browsers and by recent versions of most languages.

Flags

Flags change how the whole pattern behaves. Type them in the flags box:

Flag Effect
g find every match, not just the first (the tool always lists every match)
i ignore upper and lower case, so colou?r also finds COLOUR
m make ^ and $ match at the start and end of each line, not just of the text
s let . match line breaks too
u treat the text as Unicode, which matters for emoji and some alphabets

The m flag explains a very common confusion. ^\d{3}-\d{4}$ on three lines of text matches only if the whole text is one phone number. Add m and it matches each line that is a phone number.

Greedy and lazy matching

By default, quantifiers are greedy: they take as much text as they can. Try the pattern <.+> on <b>x</b> <i>y</i>. You might expect to get each tag, but the single match is the whole string from the first < to the last >, because .+ swallowed everything and then stepped back only as far as needed.

Add a ? after the quantifier to make it lazy, which takes as little as possible: <.+?> finds four matches, <b>, </b>, <i> and </i>. A more precise alternative is <[^>]+>, which says "an opening bracket, then any number of characters that are not a closing bracket". Being explicit about what is allowed is usually clearer and faster than relying on lazy matching.

Escaping special characters

The characters . * + ? ^ $ { } ( ) | [ ] \ have special meanings. To match one literally, put a backslash in front: \. matches a real full stop and \( a real bracket. A frequent bug is writing example.com and finding exampleXcom as well, because the dot means "any character". Write example\.com.

A short list of useful patterns

Goal Pattern Notes
Whole number ^\d+$ no sign or decimals
Number with optional decimals ^\d+(\.\d+)?$ 12, 12.5
Indian PIN code ^\d{6}$ six digits
Hex colour ^#?[0-9a-fA-F]{6}$ #d97706
Whole word cat \bcat\b skips concatenate
Extra spaces \s{2,} find double spaces
Date shape ^\d{4}-\d{2}-\d{2}$ shape only, not a real date check

Notice the last row: a regex can check the shape of text, not whether it makes sense. 2026-99-99 fits the date pattern and is not a date.

When a regex is the wrong tool

  • Email addresses. The full rules are far too complicated for a short pattern. A simple regex can reject real addresses, and a long one is hard to maintain. Check for an @ and a dot with a simple pattern, then confirm by sending a message.
  • HTML and nested structures. A regex cannot reliably parse nested tags. Use a parser.
  • Anything that must be secure. Do not rely on a pattern alone to block malicious input; validate and escape properly.
  • Dates, numbers with ranges. Check the shape with a pattern and the value with code.

Slow patterns

Some patterns can take an enormous time on certain input. Nested quantifiers such as (a+)+ try an exponential number of ways to match a failing string, an effect called catastrophic backtracking. If the tester freezes while you type, simplify the pattern or shorten the text. In production, such a pattern run on user input can lock up a server, so test with long, near-miss inputs, not just the happy path. The tester stops listing after 500 matches to keep the page responsive.

Using regex in your own code

Every language has a regex library, with small differences. In PHP, the functions preg_match, preg_match_all and preg_replace use a pattern written between delimiters; the regular expressions lesson shows them with verified output. In MySQL, the REGEXP operator filters rows, covered in LIKE and REGEXP. Browser forms can use a pattern attribute, described in form validation. Test the pattern here first, then copy it into code and adjust the delimiters or escaping for your language, remembering that in a string literal the backslashes often need doubling.

Related tools

To compare what a replacement changed in a long text, use the Text Diff Checker. To clean pasted text of hidden characters that stop a pattern from matching, use the Invisible Character Cleaner. To count matches for words and characters in a document, the Word Counter is quicker, and the Case Converter handles simple case changes without any regex at all.

Quick answers

Which flavour of regex is this? JavaScript, the one built into your browser.

Why do I only get one match? In your own code you need the g flag to find all matches. The tester always lists them all.

Why does my pattern match too much? A greedy quantifier. Make it lazy with ? or restrict the allowed characters.

How do I match a dot or a bracket? Escape it with a backslash, as \. or \(.

Is my text private? Yes. Matching happens in your browser.

Advertisement