Cookies This site keeps only what it needs to work. There is no analytics and no advertising on it today, and nothing here follows you to other sites. Read the privacy policy

Choose what to allow
+92 312 8299940Free Quote
EN – Language: English
Blog

Regex Cheat Sheet Patterns You Can Copy

A practical regex cheat sheet: character classes, anchors, quantifiers, groups, flags and ready-to-use patterns.

By Daniyal Subhani 9 min read

Character Classes: Regex cheat sheet

Character classes are enclosed by square brackets and show a set of characters where any one of them is considered a match.

Regex Cheat Sheet
Regex Cheat Sheet
PatternMatches
`.`Any character except a newline
`\d`Any digit, 0 to 9
`\D`Any non-digit
`\w`Word character: letter, digit, or underscore
`\W`Any non-word character
`\s`Whitespace: space, tab, newline
`\S`Any non-whitespace
`[abc]`a, b, or c
`[^abc]`Anything except a, b, or c
`[a-z]`Any lowercase letter
`[A-Za-z0-9]`Any letter or digit

The caret inside brackets flips the meaning. So `[^0-9]` matches anything that isn't a digit. That's a different caret from the anchor one you'll see next, which trips people up constantly.

Anchors and Boundaries

Anchors also don’t show a character and like caret symbols in character classes, these also confuse a lot of people.

PatternMatches
`^`Start of the string or line
`$`End of the string or line
`\b`A word boundary
`\B`Not a word boundary

Say you want the word "cat" but not "category." Use `\bcat\b`. The boundaries pin it to a whole word. @CAP@"category" and "scatter" won't match. Without the boundaries, both would.

Quantifiers

Quantifiers control how many times the thing before them repeats. This is where regex gets its power. Also where it gets greedy.

PatternMeaning
`*`Zero or more
`+`One or more
`?`Zero or one (optional)
`{3}`Exactly 3
`{2,5}`Between 2 and 5
`{2,}`2 or more
`*?`Lazy: as few as possible

Here’s the gotcha. Normally, quantifiers are greedy. Meaning, they are trying to capture the largest possible string that matches the pattern. So in the instance of matching the string “” against the pattern “”, the regex engine would capture “” as the match. To fix this, use “” instead so that the regex engine stops looking once it encounters the first “>” it sees. The addition of the question mark turns the quantifier into a lazy one.

Groups and Alternation

Groups are showed by parentheses. They can be used to apply a quantifier to several adjacent characters. They also allow you to capture a substring of the matched string.

PatternMeaning
`(abc)`Capturing group
`(?:abc)`Non-capturing group
`(?abc)`Named group
`a\b`a or b (alternation)
`\1`Backreference to group 1

Alternation is showed by the pipe. So the regex “cat|dog|fish” would match any of the three strings. To make this instance a little more useful, wrap the alternation in parentheses to create the regex “(cat|dog)s?” which would match “cat”, “cats”, “dog”. @CAP@“dogs”. For improved performance and easier to use capture numbers, use a non-capturing group if you don’t need to save the matched string.

Flags

Flags are used outside the regex and change the overall behavior of the regex. The effects of these flags vary by language.

FlagEffect
`i`Case-insensitive
`g`Global: find all matches, not just the first
`m`Multiline: `^` and `$` match each line
`s`Dotall: `.` also matches newlines
`x`Verbose: ignore whitespace in the pattern

The most common of these flags is the i flag. With this flag, case is ignored. So with this flag, the regex “/hello/i” would match the strings “HELLO”, “hello”, etc. In JS, to get all the matches with the .match() function you would have to use this flag.

Ready-to-Use Patterns

These are some starting point regexes to give you an idea of what to include. Tune them to fit your data as no email regex is perfect.

Email:        [A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}
URL:          https?://[^\s]+
Phone (US):   \(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}
Date (Y-M-D): \d{4}-\d{2}-\d{2}
Hex color:    #[A-Fa-f0-9]{6}\b
IPv4:         \b(?:\d{1,3}\.){3}\d{1,3}\b
Whitespace:   \s+
Digits only:  ^\d+$
Username:     ^[A-Za-z0-9_]{3,16}$
Strong-ish:   (?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}

The last one uses lookahead. The expression (?=.*\d) means “look ahead for a digit.” So you would need at least 3 of these to need a digit, lower case letter and upper case letter.

A Quick Python Note

To do regex in Python you would need to use the re module. It is relatively easy to use as it has three main functions.

import re

re.search(r"\d+", "abc123")      # first match anywhere -> '123'
re.findall(r"\d+", "a1 b22 c3")  # all matches -> ['1', '22', '3']
re.sub(r"\s+", " ", messy)       # collapse whitespace

When writing regex in Python it is best practice to use raw strings (r"...") so Python doesn’t touch your backslashes. Using raw strings is essential. Otherwise Python will interprete “\d” literally and your regex will not work. This is the most common error people make when using regex in Python.

A Real-World Example

Now let’s say you have a file with phone numbers in many formats including (555) 123-4567, 555.123.4567, and 555-123-4567. You need to extract all of these numbers. It would take a long time and be error prone to write single checks for each of these formats.

One pattern is: (?\d{3})?[-.\s]\d{3}[-.\s]\d{4}. The (?) and ? make the parentheses optional. The [-.\s]? says the separator can be a dash, a period or a space. Like this many other formats will also be captured. Some formats you may not have thought of. This is where regex becomes powerful.

Test Before You Trust

Never ship a regex you haven't tested against real and fake inputs. Paste your pattern and sample text into a tester and watch what it highlights. [Regex101](here explains every token in your pattern as you type, which is the fastest way to learn. For the full reference, [MDN's regex guide](here covers the JavaScript flavor in depth. The [Python re docs](here cover Python's.

If you're cleaning or checking text and don't want to write code, the free [Denwix text tools](here can count and format text without any regex at all.

The Bottom Line

A cheat sheet is only helpful if you use it. Begin with the basics. Reach for a group to indicate choice. Flag usage and position can be freely altered. Break large regex down into smaller parts. Don’t get caught up in the complexities and try to write a large, complicated email matcher. The best programmers also consult their cheat sheets.

Questions and Answers

What is a regex cheat sheet?

It's a quick reference of regex syntax: character classes, anchors, quantifiers, groups and flags, usually with ready-to-copy patterns. You keep it open while writing patterns instead of memorizing everything.

What does \d mean in regex?

`\d` matches any single digit, 0 through 9. Its opposite, `\D`, matches any character that isn't a digit. Add a quantifier like `\d+` to match one or more digits in a row.

What is the difference between * and + in regex?

The asterisk matches zero or more of the preceding element and could so match nothing. The plus sign matches one or more of the preceding element and is so needed to match at least one.

What does ^ mean in regex?

Anchors to the start of a line or string respectively. In a character class, [^abc] means “not any of the characters a, b, c.”

How do I match a whole word in regex?

Wrap the word with word boundaries to exclude matching a portion of a larger word. Word boundaries prevent matching a word inside a larger word.

What is greedy versus lazy matching?

If a quantifier is followed by a question mark (?), it will stop at the first match, otherwise it will match as many times as possible.

How do I make regex case-insensitive?

Adding the i flag makes the pattern case insensitive. In JavaScript use /pattern/i. In Python use re.IGNORECASE.

What is a capturing group?

Capturing groups are specified using the construct (...). The captured text can then be used or extracted. Use (?:...)) to create a non-capturing group.

How do I match an email with regex?

A more involved, yet practical instance is the email pattern [A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,}. No regular expression will capture all emails 100% of the time.

What does the g flag do?

The global flag causes the regex to find all occurrences within the string as opposed to just the first. It’s key to note that in JavaScript the method .match() behaves differently with and without the flag.

How do I use regex in Python?

To use a module other than the default use import re. Use re.search(), re.findall(), or re.sub() to conduct your regex. Use raw strings when defining your regex by adding an r before your string. Thus, to search for one or more digits you would use r"\d+"

Why should I use raw strings in Python regex?

Using raw strings allows Python to not interpret the backslashes thus giving you more functionality when defining regex.

What does \b mean in regex?

`\b` matches a word boundary, the position between a word character and a non-word character. It matches a position, not a character. It has zero width.

How do I match multiple options in regex?

Use pipe | to indicate options, for instance cats or dogs is expressed as (cat|dog).

What is a lookahead in regex?

Lookaheads are expressed as (?=...). In password validation you may use (?=.*\d) to ensure a digit is present in the password.

How do I escape special characters in regex?

To include special characters in a search pattern, escape them with a backslash. To search for a period or question mark, use . or ?, respectively. Inside character classes, most special characters retain no special meaning.

What is the difference between . and \. in regex?

A dot matches any single character. A backslash followed by a dot, ., matches a literal period. Most people’s trouble with overly loose patterns stems from forgetting to include the backslash.

How do I match a number range like 2 to 5 times?

Use a quantifier with braces: `{2,5}` matches the preceding item 2 to 5 times. `{3}` means exactly 3, and `{2,}` means 2 or more.

Are regex patterns the same in every language?

Features such as lookbehinds, assertions and named groups differ across flavors of regex. To ensure your regex works as expected, always test it in the language you’re going to implement it in.

How do I test a regex pattern?

Regex101 is a great online resource. It supports many languages, highlights the parts of the regex that match. Gives a description of each token as you type it in. Use tricky invalid inputs to test your regex before using it in production.

What does $ mean in regex?

Dollar sign anchors to the end of a line. Thus, \d+$ would match digits at the end of a line. If \d+ is anchored to the beginning of a line with ^, the whole line would match that digit sequence.

How do I match an optional character in regex?

Adding a question mark after the letter makes the letter optional, so, for instance, colou?r would match both color and colour. The question mark in this case means the preceding item in the class is optional.

What is the difference between () and []?

Round brackets are used to define a sequence to be captured. square brackets define a character class to be evaluated.

How do I match any whitespace in regex?

Use \s which matches spaces, tabs and new lines. To collapse runs of whitespace use \s+ to match one or more.

Can I use regex to find and replace?

Yes. Most editors and programming languages support regex in find and replace. The capturing group is useful to reference in the replacement text.

Why is my regex matching too much?

Probably a greedy quantifier. The .+ matches as large of a pattern as possible. Use .+? to match the smallest possible pattern.

How do I match a specific number of digits?

Use brackets. \d{4} will match exactly 4 digits and is useful in finding years. \d{2,4} will match between 2-4 digits.

What is a non-capturing group good for?

Use (?:...) to achieve the same result as (...) but not save the match. Use this when grouping is necessary to use a quantifier or option.

Video guide

Video Guide: Regex Cheat Sheet

This brief video shows each step from start to finish. Choose your language below, and switch on captions if they help.

Try It in Your Browser

Open the free Regex Tester and do it now, right in your browser.

Prefer Denwix on GoogleReview Denwix on Google