Regex Cheat Sheet: Practical Patterns for Everyday Tasks

Questo contenuto è in inglese.

Regular expressions look cryptic at first, but a small set of symbols covers most everyday text matching. This cheat sheet explains the building blocks, then gives practical patterns for emails, dates, UK postcodes and URLs, with caveats so you know where each one falls short.

The building blocks

A regular expression describes a pattern that a string may or may not match. Literal characters match themselves, so cat matches the word cat. The special symbols do the interesting work. A full stop matches any single character except a line break. Square brackets define a set, so [aeiou] matches any one vowel. A caret inside brackets negates the set, so [^0-9] matches anything that is not a digit.

Quantifiers control repetition. A question mark makes the preceding item optional, a plus sign requires one or more, and an asterisk allows zero or more. Curly braces give exact counts, so \d{4} matches four digits. Anchors fix a match to a position: a caret marks the start of the string, and a dollar sign marks the end.

Shorthand classes worth memorising

Shorthand classes save a lot of typing. Learn these four first, because you will use them in almost every pattern.

  • \d matches a digit, the same as [0-9]
  • \w matches a letter, digit or underscore
  • \s matches any whitespace, including spaces and tabs
  • \b matches a word boundary, so \bcat\b will not match the start of category

Negated classes and escaping

Uppercase versions negate the class, so \D matches a non-digit and \S matches a non-space. Escape a special character with a backslash when you want it treated literally, so \. matches a real full stop and \? matches a question mark. Forgetting to escape is the most common reason a pattern matches more than you intended.

Greedy versus lazy matching

By default, quantifiers are greedy and grab as much text as they can. Applied to HTML, the pattern <.+> matches from the first less-than sign all the way to the last greater-than sign, which is rarely what you want. Adding a question mark makes it lazy, so <.+?> stops at the first closing bracket. Test this with real input, because greedy matches often look right on short examples and fail on longer text.

Email addresses

A fully accurate pattern for the email standard is so long that almost nobody uses it. A practical pattern checks the basic shape instead: some characters, an at sign, a domain part containing a full stop, and no spaces. The pattern below does that job for form hints and quick filters.

^[^\s@]+@[^\s@]+\.[^\s@]+$

Caveats matter here. It accepts addresses that do not exist, such as [email protected], because checking existence needs a mailbox. It also lets through some malformed addresses, such as double full stops in the domain. The only reliable test is to send a confirmation message and ask the person to click a link.

UK dates

Dates are awkward because the same string can mean different things in different countries. For day, month and year written as dd/mm/yyyy, this pattern checks the layout and the plausible ranges for day and month.

^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[0-2])/[0-9]{4}$

The pattern accepts 31 February and 30 April, so check the calendar too, perhaps with a date library after the match. For ISO dates in the form 2026-10-15, use this pattern instead, which is easier to validate and sorts correctly as plain text.

^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$

UK postcodes

UK postcodes follow a pattern of one or two letters, a digit, an optional letter or digit, then a space and a digit followed by two letters. The pattern below accepts the common forms, with or without the space. Matches include SW1A 1AA, M1 1AE, B33 8TH and W1A 0AX.

^[A-Z]{1,2}[0-9][A-Z0-9]? ?[0-9][A-Z]{2}$

Caveats: the pattern does not know which postcodes exist, so a well-formed string can still be invalid. It rejects the special Girobank code GIR 0AA, and it does not check the letters that are restricted in certain positions. Use it to catch typos, then confirm against an address lookup service where accuracy matters. Lowercase input needs a case-insensitive flag, or convert it to uppercase first.

Web addresses

For a quick check that text looks like a web address, look for a scheme followed by at least one character with no spaces. This pattern accepts http and https addresses, which makes it useful for spotting links in longer text.

^https?://\S+$

This pattern does not check that the domain is valid, and it accepts characters that a real address would encode. When you need to pull links out of a document, matching the scheme and stopping at whitespace or a closing quotation mark is often more practical than trying to validate the whole address.

Testing and common mistakes

Test every pattern with a regex tester, using examples that should match and examples that should not. Flags such as global, case-insensitive and multiline change behaviour, so note which ones your code uses. Remember that backslashes must be doubled when a pattern sits inside a string literal in many languages.

  • Forgetting to escape the full stop, so a dot matches any character
  • Using greedy quantifiers when lazy ones were needed
  • Forgetting anchors, so a pattern matches part of a longer string
  • Assuming shorthand classes behave identically in every engine
  • Skipping edge cases such as empty input and extra spaces

Strumenti citati in questa guida

Domande frequenti

Why does my regex match too much text?

The usual cause is greedy quantifiers, which take as much text as they can while still allowing the rest of the pattern to match. A pattern made of a less-than sign, any characters, and a greater-than sign will run from the first opening tag to the last closing one. Make the quantifier lazy by adding a question mark, use a negated character class that excludes the closing character, or anchor the pattern more tightly.

Do I need a regex to validate email addresses?

A simple pattern can catch obvious mistakes such as missing at signs or spaces, which is useful in forms and data cleaning. However, no short pattern can confirm that an address is deliverable. For real validation, send a confirmation message and ask the person to click a link. Pattern checks are best treated as a first filter that stops typing errors from reaching your system.

Why does the date pattern accept 31 February?

A pattern checks the layout of text, not the calendar. It can confirm that the day is between 1 and 31 and the month between 1 and 12, but it cannot know how many days each month contains or whether a year is a leap year. After matching, parse the string with a date library, which will reject impossible dates. This two-step approach catches both layout errors and calendar errors.

Is there a single regex for every UK postcode?

A single pattern can match the common postcode shapes, and the one in this guide handles most real inputs. However, a fully strict pattern gets very long because certain letters are restricted in certain positions, and the Girobank code GIR 0AA is a special case. Postcodes are also reassigned over time. For accuracy, combine the pattern with a postcode lookup service, particularly when addresses matter for deliveries.

Should I use the same regex in JavaScript and Python?

Often yes, but check the details. Core syntax, including character classes, quantifiers and anchors, behaves much the same across languages. Differences appear in lookbehind support, named groups, Unicode handling of shorthand classes, and how flags are set. Test the pattern in the language you will actually use, rather than assuming identical results across every engine.