Regular expressions (regex) cheat sheet

This regex cheat sheet brings together the building blocks of regular expressions, from special characters and anchors, through character classes, quantifiers, groups, and lookahead, to replacement syntax, ready-made patterns for input validation, and use with grep, sed, and awk, with a short explanation of each pattern. You can search for a pattern, filter by category, and copy it with one click.

Basics and anchors

  • cat

    Most characters in a regular expression match themselves, so the pattern cat matches the letters cat anywhere in the text, even inside a longer word. Matching is case-sensitive by default, so Cat does not match cat without the i flag.

    Example: Pattern: cat | Input: cat Cat concatenate | Match: cat, and the cat inside concatenate

  • .

    The dot matches any single character except a line break. To make the dot match line breaks as well, turn on the s flag.

    Example: Pattern: c.t | Input: cat c-t ct | Match: cat, c-t

  • \.

    A backslash before a special character removes its special meaning, so the character matches only itself. A common mistake is writing the dot in a domain name without a backslash, which makes it match any character.

    Example: Pattern: example\.com | Input: example.com examplexcom | Match: example.com only

  • \\

    Matches a single backslash in the text. When the pattern is written inside a string in code, as in PHP or JavaScript, every backslash in the pattern is written twice in the string, so one backslash in the text sometimes takes four backslashes in the string.

    Example: Pattern: C:\\Users | Input: C:\Users | Match: C:\Users

  • . ^ $ * + ? ( ) [ ] { } | \

    These are the special characters in a regular expression. To match one of them as a regular character, add a backslash before it, for example \? or \(. Inside square brackets most of these characters lose their special meaning, so [.?] matches a dot or a question mark.

  • ^

    An anchor that matches the start of the text, and with the m flag also the start of every line. The anchor does not match a character, but a position.

    Example: Pattern: ^www | Input: www.example.com | Match: www, only when it is at the start of the text

  • $

    An anchor that matches the end of the text, and with the m flag also the end of every line. In PHP and Python, the anchor also matches before a single line break at the end of the text.

    Example: Pattern: \.php$ | Input: index.php | Match: .php; no match in index.php.bak

  • ^\d+$

    Combining ^ at the start and $ at the end requires the whole text to match the pattern, not just part of it. This is the basis of form input validation: without the anchors, the pattern \d+ also matches text that merely contains digits.

    Example: Pattern: ^\d+$ | Input: 12345 | Match: 12345; no match in 123a

  • \b

    Word boundary: a position between a word character (a letter, a digit, or an underscore) and another character or the edge of the text. Used to search for a whole word. In JavaScript, the boundary counts only ASCII letters as word characters and does not recognize words with accented letters such as café, while in Python and in PHP with the u flag it recognizes letters in every language.

    Example: Pattern: \bcat\b | Input: cat cats concat | Match: the first cat only

  • \B

    The opposite of \b: a position that is not a word boundary, that is, inside a word. Used to find a sequence that appears only in the middle of a word.

    Example: Pattern: \Bcat\B | Input: cat concatenate | Match: the cat inside concatenate

  • \A

    Matches only the start of the text, even when the m flag is on, unlike ^. Supported in PHP, Python, and grep -P, and not supported in JavaScript.

  • \z

    Matches the absolute end of the text, ignoring a line break at the end. Recommended for strict input validation in PHP, where $ also matches before a single line break at the end. In Python, the equivalent is \Z, and in JavaScript you use $ without the m flag.

  • \r?\n

    Matches a line break, both in the Windows format (\r\n) and in the Linux and macOS format (\n). The sequence \t matches a tab, and \n alone does not catch the \r character left at the end of lines in files from Windows.

  • \Q...\E

    Everything between \Q and \E is read as plain text, special characters included, so there is no need to add a backslash before each of them. Supported in PHP and grep -P, and not supported in JavaScript and Python.

    Example: Pattern: \Q1+1=2\E | Input: 1+1=2 | Match: 1+1=2

Character classes and Unicode

  • [abc]

    Character class: matches one character from the list in the brackets. A class always matches exactly one character, so for several characters add a quantifier after it, for example [abc]+.

    Example: Pattern: gr[ae]y | Input: gray grey groy | Match: gray, grey

  • [^abc]

    Negated class: matches any character that is not in the list, including a space and a line break. The ^ sign negates only when it is the first character inside the brackets.

    Example: Pattern: [^0-9] | Input: a1b2 | Match: a, b

  • [a-z]

    Character range: matches any lowercase Latin letter from a to z. The range is based on the order of characters in the character table, so [a-z] does not include uppercase letters or letters with marks such as é.

  • [A-Za-z0-9]

    Several ranges in one class: an uppercase Latin letter, a lowercase Latin letter, or a digit. You can combine ranges and single characters in the same class.

  • [a-z0-9._-]

    A hyphen at the start or end of the class is read as a regular hyphen, not a range, and a dot inside a class is a regular dot. This class matches lowercase letters, digits, the dot, the underscore, and the hyphen, for example in file names.

  • \d

    Matches a single digit. In JavaScript, and in PHP without the u flag, it is equivalent to [0-9]. In Python and in PHP with the u flag, it also includes digits from other scripts, so to check only the digits 0 to 9, use [0-9]. In grep -E, sed, and awk, \d is not supported and is read as the letter d, so use [0-9] there.

    Example: Pattern: \d+ | Input: room 204 floor 3 | Match: 204, 3

  • \D

    Matches any character that is not a digit, including letters, spaces, and symbols. Useful for removing everything except digits from a phone number before validation.

    Example: Pattern: \D | Replacement: (empty) | Input: 050-123 4567 | Result: 0501234567

  • \w

    Matches a word character: a Latin letter, a digit, or an underscore, similar to [A-Za-z0-9_]. In JavaScript, it does not include accented letters such as é, while in Python and in PHP patterns with the u flag it also includes letters from other languages.

  • \W

    Matches any character that is not a word character, such as a space, a dot, or a hyphen. In JavaScript, an accented letter such as é also counts as a non-word character here.

  • \s

    Matches a single whitespace character: a space, a tab, a line break, and similar characters. Suits splitting text into words or cleaning up double spaces.

    Example: Pattern: \s+ | Input: a b | Match: the three spaces between the letters

  • \S

    Matches any character that is not whitespace. The sequence \S+ matches a continuous run without spaces, such as a word, an address, or a number.

  • [\s\S]

    Matches any character, including a line break. Used in JavaScript and other engines when you need a dot that crosses lines and cannot turn on the s flag.

  • [[:alpha:]]

    POSIX class for letters. Other classes: [[:digit:]] for digits, [[:alnum:]] for letters and digits, [[:space:]] for whitespace, [[:upper:]] and [[:lower:]] for uppercase and lowercase letters, and [[:punct:]] for punctuation. Supported in grep, sed, awk, and PHP, and not supported in JavaScript and Python. The double brackets are required.

  • \p{L}

    Matches any letter in any language, including accented Latin letters, Greek, Cyrillic, Arabic, and Hebrew. JavaScript requires the u flag, and PHP requires the u flag when the text is UTF-8. Python's standard re module does not support this syntax. The form \P{L} matches any character that is not a letter.

    Example: Pattern: \p{L}+ | Input: café Hello 123 | Match: café, Hello

  • [\u00C0-\u024F]

    Matches any character in the letters part of the Latin-1 Supplement and in the Latin Extended-A and B ranges of Unicode: accented letters such as é, ñ, and ü, and also the × and ÷ signs, which sit inside the range. The \u syntax is supported in JavaScript and Python.

    Example: Pattern: [\u00C0-\u024F]+ | Input: naïve café | Match: ï, é

  • [\x{00C0}-\x{024F}]

    The same range in the syntax of PHP and grep -P. In PHP, add the u flag, for example /[\x{00C0}-\x{024F}]/u, so the text is handled as UTF-8.

  • [À-ÖØ-öø-ÿ]

    Matches one letter from the Latin-1 Supplement, such as é, ñ, or ü, and skips the × and ÷ signs, which sit between the ranges. The class does not cover letters from Latin Extended, such as ő or ł, and suits a quick check of Western European letters. In PHP, add the u flag.

  • \p{Latin}

    Matches any character of the Latin script according to Unicode, including accented letters. Supported in PHP with the u flag and in grep -P. In JavaScript, the syntax is different: \p{Script=Latin} with the u flag.

  • \p{Script=Latin}

    The JavaScript syntax for the Latin script, which works only with the u flag, for example /\p{Script=Latin}+/u. In JavaScript, the short form \p{Latin} causes an error.

  • [\u0300-\u036F]

    Matches combining diacritical marks, such as accents. Accented letters are usually stored as single characters, so first split them into a letter and a mark with NFD normalization, for example normalize("NFD") in JavaScript, and then replacing with an empty string removes the accents and keeps the letters. In PHP, write [\x{0300}-\x{036F}] with the u flag.

    Example: Pattern: [\u0300-\u036F] | Replacement: (empty) | Input: crème brûlée after NFD normalization | Result: creme brulee

Quantifiers

  • *

    Zero or more of the preceding item. Because zero times also counts as a match, the pattern a* also matches an empty string.

    Example: Pattern: ab*c | Input: ac abc abbbc | Match: ac, abc, abbbc

  • +

    One or more of the preceding item. This is the most common quantifier for sequences, such as \d+ for a number or \s+ for spaces.

    Example: Pattern: ab+c | Input: ac abc abbbc | Match: abc, abbbc

  • ?

    The preceding item is optional: zero times or once. After a group in parentheses, the sign makes the whole group optional.

    Example: Pattern: colou?r | Input: color colour | Match: color, colour

  • {3}

    An exact number of repetitions. Without anchors, the pattern \d{3} also matches three digits inside a longer number, so for an exact check combine it with ^ and $ or with \b.

    Example: Pattern: \d{3} | Input: 12 1234 | Match: 123 out of 1234

  • {2,}

    At least the given number of repetitions, with no upper limit.

    Example: Pattern: \d{2,} | Input: 1 12 12345 | Match: 12, 12345

  • {2,4}

    A range of repetitions, from the minimum to the maximum, both ends included. The quantifier is greedy and takes as many repetitions as possible.

    Example: Pattern: \d{2,4} | Input: 123456 | Match: 1234, 56

  • {0,3}

    Up to three repetitions, zero included. The short form {,3} is not supported in every engine, and JavaScript reads it as plain text, so it is best to write the minimum 0 explicitly.

  • *?

    Lazy quantifier: zero or more repetitions, but as few as possible. A regular quantifier is greedy and takes as many as possible, so <.*> catches all the text from the first < sign to the last > on the line.

    Example: Pattern: <.*?> | Input: <b>text</b> | Match: <b>, </b>; with <.*> the match is the whole string

  • +?

    The lazy version of +: at least one repetition, but as few as possible. Usually used before a closing character, for example ".+?" for a string between quotes.

    Example: Pattern: ".+?" | Input: "a" and "b" | Match: "a", "b"

  • ??

    The lazy version of ?: the engine first tries to skip the item, and adds it only if the match fails without it. Rarely used, and worth knowing so you do not mistake it for a typo.

  • {2,4}?

    The lazy version of a repetition range: starts from the minimum and adds repetitions only when needed.

    Example: Pattern: \d{2,4}? | Input: 123456 | Match: 12, 34, 56

  • *+

    Possessive quantifier: takes as many repetitions as possible and gives none back, even if the rest of the pattern fails. Prevents needless backtracking and improves performance. Supported in PHP, grep -P, and newer versions of Python, and not supported in JavaScript.

    Example: Pattern: \d*+5 | Input: 125 | Match: none, because \d*+ also took the digit 5

  • ++

    The possessive version of +: at least one repetition, without giving characters back. Similarly, there are also ?+ and {n,m}+. Support is the same as for *+.

  • (?>...)

    Atomic group: once its content has matched, the engine does not go back to try other alternatives inside it. Used to guard against excessive backtracking, and supported in the same engines that support possessive quantifiers.

  • (a+)+$

    An example of a dangerous pattern: a quantifier inside a quantifier on the same characters causes catastrophic backtracking when there is no match. On a run of a characters ending in another character, the check time doubles with every extra character, and a few dozen characters can take minutes or hours. In PHP, the check stops at the backtracking limit and the function returns false instead of a result. Avoid nested quantifiers on overlapping content and limit the input length.

Groups and backreferences

  • (abc)

    Capturing group: combines several items into one and saves the matched text, so you can retrieve it in code or use it in a replacement. Groups are numbered from 1 by the order of their opening parentheses.

    Example: Pattern: (\d{3})-(\d{4}) | Input: 123-4567 | Match: 123-4567, group 1: 123, group 2: 4567

  • (ab)+

    A quantifier after a group applies to the whole group. When a capturing group repeats several times, it keeps only the last repetition.

    Example: Pattern: (ab)+ | Input: ababab | Match: ababab, group 1: ab

  • (?:abc)

    Non-capturing group: combines items for a quantifier or alternatives, but does not save the text and gets no number. Recommended wherever you do not need the text itself, because it keeps the numbering of the other groups simple.

    Example: Pattern: (?:https?|ftp):// | Input: https://example.com | Match: https://, with no saved group

  • (?<year>\d{4})

    Named group: the text is retrieved by name rather than by number, which makes the code clearer and keeps it working when you add groups. Supported in JavaScript and PHP. In Python, the syntax is (?P<year>\d{4}).

    Example: Pattern: (?<year>\d{4})-(?<month>\d{2}) | Input: 2026-11 | Match: year=2026, month=11

  • (?P<year>\d{4})

    The Python syntax for a named group, also supported in PHP. In Python code, you retrieve the value with match.group("year").

  • \1

    Backreference: matches the exact same text that group 1 captured. Used to find doubled characters or words and to match identical opening and closing quotes.

    Example: Pattern: (\w)\1 | Input: hello book | Match: ll, oo

  • \k<name>

    A backreference by group name. Supported in JavaScript and PHP. In Python, the syntax is (?P=name).

    Example: Pattern: (?<q>['"]).*?\k<q> | Input: "abc" 'xy' | Match: "abc", 'xy'

  • (?P=name)

    A backreference by name in the Python syntax, also supported in PHP. Matches the same text captured by the named group, which is defined with the (?P<name>...) syntax.

  • cat|dog

    Alternatives: matches one of the patterns separated by a vertical bar. The engine tries the alternatives from left to right and picks the first that matches, so when one alternative is the start of another, write the longer one first.

    Example: Pattern: cat|dog | Input: hotdog cat | Match: dog, cat

  • ^(?:jpg|png)$

    The vertical bar separates everything on its left from everything on its right, so ^jpg|png$ means jpg at the start of the text or png at its end. A group around the alternatives limits them, and the anchors apply to all of them.

  • ((\d{3})-(\d{4}))

    In nested groups, numbering follows the order of the opening parentheses from left to right, so the outer group gets the lower number. Group 0 always stands for the whole match.

    Example: Pattern: ((\d{3})-(\d{4})) | Input: 123-4567 | Match: group 1: 123-4567, group 2: 123, group 3: 4567

Lookahead and lookbehind (lookaround)

  • (?=...)

    Lookahead: checks that the text in the parentheses follows the current position, but does not include it in the match. Supported in JavaScript, PHP, Python, and grep -P, and not supported in grep -E and sed.

    Example: Pattern: \d+(?=%) | Input: 50% 30 | Match: 50, without the % sign

  • (?!...)

    Negative lookahead: the match succeeds only when the text in the parentheses does not follow the current position. Used for exclusions, for example of addresses that start with www.

    Example: Pattern: ^(?!www\.).+ | Input: example.com | Match: example.com; no match in www.example.com

  • (?<=...)

    Lookbehind: checks that the text in the parentheses comes before the current position, without including it in the match. In Python, the content must have a fixed length. PHP also allows alternatives of different lengths, and newer versions allow a limited variable length such as a{1,3}, but unbounded quantifiers such as + and * are not allowed. In JavaScript, in current browsers and environments, there is no length limit.

    Example: Pattern: (?<=\$)\d+ | Input: price $40 | Match: 40

  • (?<!...)

    Negative lookbehind: the match succeeds only when the text in the parentheses does not come before the current position. The length limits and support are the same as for a regular lookbehind.

    Example: Pattern: (?<!-)\b\d+\b | Input: -5 7 | Match: 7

  • ^(?=.*error)(?=.*disk).*

    Several lookaheads in a row at the start of the pattern create an "and" condition: the line matches only if all the words appear in it, in any order. This is also the way to check several password rules.

    Example: Pattern: ^(?=.*error)(?=.*disk).* | Input: disk error on sda | Match: the whole line

  • user=\K\w+

    \K drops everything matched before it from the match, so it serves as an alternative to lookbehind even when the preceding part does not have a fixed length. Supported in PHP and grep -P, and especially useful with grep -oP to pull a value out of a line.

    Example: Pattern: user=\K\w+ | Input: id=5 user=admin | Match: admin

Flags

  • i

    Case-insensitive matching: A and a count as the same. In JavaScript and PHP you write /abc/i, in Python re.I, and in grep the -i option.

    Example: Pattern: /hello/i | Input: HeLLo | Match: HeLLo

  • g

    Global search, in JavaScript only: without the flag, replace replaces only the first match and match returns only that one. In PHP, preg_replace replaces all matches by default, and to find all of them you use preg_match_all. In Python, re.sub and re.findall work on all matches.

    Example: Pattern: /a/g | Replacement: b | Input: banana | Result: bbnbnb

  • m

    Multiline mode: the ^ and $ anchors match the start and end of every line, not only the start and end of the text. In Python, the flag is re.M.

    Example: Pattern: /^\d+/gm | Input: line 1: 10 abc, line 2: 20 xyz | Match: 10, 20; without m: 10 only

  • s

    The dot also matches a line break, so .* can cross lines. Supported in JavaScript, PHP, and Python (re.S).

  • u

    Unicode mode. In JavaScript, the flag is required for \p{...} and makes syntax checks stricter. In PHP, the flag makes the pattern and the text be handled as UTF-8, and it is essential for working with non-ASCII text such as accented letters. Text that is not valid UTF-8 makes the PHP function fail, not just find no match. In Python, strings are Unicode by default.

  • x

    Extended mode: spaces in the pattern are ignored, and you can add comments after the # sign, so a long pattern can be written over several readable lines. A space needed for the match is written as \s or [ ]. Supported in PHP and Python (re.X), and not supported in JavaScript.

  • (?i)

    A flag inside the pattern itself, useful when you cannot set flags, for example in a software settings field. You can combine several flags, such as (?im). Supported in PHP, Python, and grep -P, and not supported in JavaScript. In Python, the flag must appear at the start of the pattern.

    Example: Pattern: (?i)hello | Input: HELLO | Match: HELLO

  • (?i:www)

    A flag that applies only to part of the pattern, inside the group. Supported in PHP and Python, and in JavaScript only in newer browsers and environments.

    Example: Pattern: (?i:www)\.example\.com | Input: WWW.example.com | Match: WWW.example.com

  • #^https?://#i

    In PHP, the pattern is written between delimiter characters, and the flags come after the closing delimiter. When the pattern contains slashes, as in URLs, it is easier to use another delimiter such as #, so there is no need to add a backslash before every /.

  • new RegExp("\\d+", "g")

    Creating a pattern in JavaScript from a string, for example when the pattern is built from input. In a string, every backslash is written twice, and "\d+" without doubling becomes d+. When you include user input, add a backslash before its special characters.

  • r"\d+"

    In Python, it is best to write patterns as raw strings, with r before the quotes, so the backslashes reach the pattern as they are. Without r, sequences such as \b are read as a control character of the string itself.

Replacement syntax

  • $1

    Inserts what group 1 captured into the replacement text, and likewise $2 for group 2. Supported in JavaScript and PHP. In PHP, write the replacement string in single quotes, because in double quotes PHP reads forms such as ${1} as a variable and \1 as a control character.

    Example: Pattern: (\d{4})-(\d{2})-(\d{2}) | Replacement: $3/$2/$1 | Input: 2026-11-24 | Result: 24/11/2026

  • \1

    The backslash syntax for inserting a group in a replacement. Supported in Python, sed, and PHP, and not supported in JavaScript. In Python, use a raw string, for example r"\2 \1".

    Example: Pattern: (\w+) (\w+) | Replacement: \2 \1 | Input: hello world | Result: world hello

  • ${1}

    In PHP, the curly braces separate the group number from the digit after it: ${1}0 means group 1 followed by the digit 0, not group 10. In Python, the equivalent is \g<1>0.

    Example: Pattern: (\d+) | Replacement: ${1}0 | Input: 5 | Result: 50

  • $<name>

    Inserting a named group in a JavaScript replacement. In PHP, preg_replace replacements do not support names, so you use the group number.

    Example: Pattern: (?<user>\w+)@example\.com | Replacement: $<user> | Input: dana@example.com | Result: dana

  • \g<name>

    Inserting a group in a Python replacement, by name or by number, for example \g<1>. This form prevents confusion when a digit follows the group.

  • $&

    Inserts the whole matched text, in JavaScript. Useful for wrapping the match in characters without needing a group.

    Example: Pattern: \d+ | Replacement: [$&] | Input: a1b22 | Result: a[1]b[22]

  • $0

    The whole matched text, in PHP, where you can also write \0. In Python, the equivalent is \g<0>, while \0 inserts a control character there rather than the match.

  • &

    In sed, the & sign in the replacement text stands for the whole match. To write & as a regular character, add a backslash before it.

    Example: Pattern: [0-9]+ | Replacement: (&) | Input: id 42 | Result: id (42)

  • $$

    Inserts a literal $ sign into the replacement text in JavaScript, without reading it as a group reference.

    Example: Pattern: (\d+) USD | Replacement: $$$1 | Input: 40 USD | Result: $40

  • \U\1

    In GNU sed, \U converts what follows it to uppercase, \L to lowercase, and \E stops the conversion. Also supported in some code editors, and not supported in JavaScript, PHP, and Python, where you use a function.

    Example: Pattern: ^([a-z]) | Replacement: \U\1 | Input: hello | Result: Hello

  • preg_replace_callback

    When the replacement requires a calculation, pass a function instead of a string: in PHP with preg_replace_callback, in JavaScript as the second argument of replace, and in Python as the second argument of re.sub. The function receives the match and the groups and returns the replacement text.

Ready-made patterns

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

    A simplified email address check: text without spaces, @, a domain, and a dot. The check is lenient on purpose and also accepts addresses with non-Latin characters, and the only way to confirm that an address exists is to send it a verification message.

    Example: Input: user@example.co.il | Match: yes; no match in user@example

  • ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$

    A more detailed email check that allows only Latin letters, digits, and common symbols, with an extension of at least two letters. The check rejects addresses with non-Latin letters and does not cover every case the standard allows.

  • ^https?://[A-Za-z0-9.-]+(?::\d{1,5})?(?:[/?#]\S*)?$

    A simplified check for a website address that starts with http or https, with an optional port, path, and parameters. The pattern checks only the structure and does not check that the domain name is valid. Convert a domain name with non-Latin characters to Punycode first.

    Example: Input: https://example.com:8080/a?x=1 | Match: yes; no match in ftp://example.com

  • https?://[^\s<>"']+

    Pulls website addresses out of free text: from http or https up to a space, a double or single quote, or a < or > sign. A punctuation mark attached to the end of the address, such as a period at the end of a sentence, is included in the match and is best removed separately.

    Example: Pattern: https?://[^\s<>"']+ | Input: see https://example.com/page here | Match: https://example.com/page

  • ^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$

    An exact IPv4 address check: four numbers from 0 to 255, without leading zeros. The pattern rejects addresses such as 256.1.1.1 and 01.2.3.4.

    Example: Input: 192.168.1.1 | Match: yes; no match in 192.168.1.256

  • \b(?:\d{1,3}\.){3}\d{1,3}\b

    A quick way to find IPv4 addresses in text, for example in a log file. The pattern does not check the range and also matches 999.1.1.1, so it suits extraction rather than validation.

    Example: Pattern: \b(?:\d{1,3}\.){3}\d{1,3}\b | Input: from 10.0.0.5 port 22 | Match: 10.0.0.5

  • ^(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}$

    A simplified check for an IPv6 address in full form: eight groups of up to four hexadecimal digits. The pattern does not accept addresses shortened with ::, and for a full check use a dedicated function of your programming language.

    Example: Input: 2001:db8:0:0:0:0:0:1 | Match: yes; no match in 2001:db8::1

  • ^(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}$

    MAC address: six pairs of hexadecimal digits, separated by colons or hyphens. The pattern also accepts a mix of both separator types in the same address.

    Example: Input: 00:1A:2B:3C:4D:5E | Match: yes

  • ^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63}$

    Domain name: labels of up to 63 characters that do not start or end with a hyphen, and an extension of letters only. Convert a domain name with non-Latin characters to Punycode first, and an extension in another script requires widening the last part.

    Example: Input: shop.example.co.il | Match: yes; no match in example-.com

  • ^(?:[A-Za-z0-9-]+\.)*example\.com$

    Checks that an address is example.com or one of its subdomains. The anchors and the dot before example are essential: without the $ anchor, example.com.evil.net also passes, and without the dot, badexample.com also passes.

    Example: Input: shop.example.com | Match: yes; no match in example.com.evil.net

  • ^(?:\+972-?|0)5\d-?\d{3}-?\d{4}$

    An Israeli mobile phone number: the 05X prefix with a leading 0 or with +972, and optional hyphens. Remove spaces and parentheses from the input first, and do not make the check any stricter, so valid numbers are not rejected.

    Example: Input: 050-1234567, +972501234567 | Match: both numbers

  • ^\d{9}$

    The structure of an Israeli ID number: exactly nine digits. Pad a shorter number with leading zeros before the check. The pattern checks only the structure and does not check the check digit, which requires a calculation in code.

    Example: Pattern: ^\d{9}$ | Input: 012345678 | Match: yes; no match in 12345678 (pad it to 012345678)

  • ^\d{7}$

    An Israeli postal code: exactly seven digits. Remove spaces from the input before the check.

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

    A date in DD/MM/YYYY format, with a day from 01 to 31 and a month from 01 to 12. The pattern does not check the number of days in each month or leap years, so 31/02/2026 passes, and a full check is done in code. In JavaScript, when the pattern is written between slashes, add a backslash before every /.

    Example: Input: 24/11/2026 | Match: yes; no match in 24/13/2026

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

    A date in ISO format, YYYY-MM-DD, the standard format in databases and APIs. Here too, the number of days in each month is not checked.

    Example: Input: 2026-11-24 | Match: yes

  • ^([01]\d|2[0-3]):[0-5]\d$

    Time in 24-hour format, HH:MM, from 00:00 to 23:59. For seconds, add (:[0-5]\d) before the $ anchor, and with ? after it the seconds become optional.

    Example: Input: 23:59 | Match: yes; no match in 24:00

  • ^#(?:[0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$

    A hexadecimal color code in CSS, in the short 3-character form or the full 6-character form. To also support transparency, add the lengths 4 and 8.

    Example: Input: #1a2B3c, #fff | Match: both; no match in #12345

  • ^[a-z0-9]+(?:-[a-z0-9]+)*$

    A slug for a page URL: lowercase Latin letters and digits, with a single hyphen between words, and no hyphen at the start, at the end, or in a row. For slugs in other scripts, add that script's letters to both classes.

    Example: Input: my-first-post | Match: yes; no match in my--post

  • ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$

    A password of at least 8 characters, with a lowercase letter, an uppercase letter, a digit, and a special character, using lookaheads. Password length adds more to strength than composition rules, so consider requiring a longer password. The pattern does not work in grep -E.

    Example: Input: Passw0rd! | Match: yes; no match in password1

  • ^\s+|\s+$

    Removes spaces from the start and end of the text, by replacing with an empty string. In JavaScript, the g flag is needed to handle both sides, but the built-in trim function is usually simpler.

    Example: Pattern: ^\s+|\s+$ | Replacement: (empty) | Input: " hello " | Result: "hello"

  • [ \t]{2,}

    Finds a run of two or more spaces or tabs, to replace with a single space. The pattern does not touch line breaks, unlike \s{2,}, which also joins lines.

    Example: Pattern: [ \t]{2,} | Replacement: one space | Input: a b | Result: a b

  • ^[ \t]*$

    An empty line or a line that contains only spaces, with the m flag. Useful for finding empty lines in a file or counting them.

  • \b(\w+)\s+\1\b

    Finds a word repeated twice in a row, such as "the the". Replacing with $1 leaves one word, and with the i flag it also finds repeats with different case. In JavaScript, the pattern does not recognize words with accented letters, because \w and \b cover ASCII letters only.

    Example: Pattern: \b(\w+)\s+\1\b | Input: the the cat | Match: the the

  • <[^>]+>

    Matches one HTML tag, opening or closing, and is used to quickly strip tags from a simple piece of text. Warning: do not parse a full HTML document with regular expressions, because the document structure is too complex. For parsing, filtering, and protection against malicious code, use a dedicated HTML parsing library.

    Example: Pattern: <[^>]+> | Replacement: (empty) | Input: <p>Hello <b>world</b></p> | Result: Hello world

  • <a\s[^>]*href="([^"]*)"

    Pulls the address out of a link, for a quick check of a code snippet. The pattern assumes double quotes around the address and does not handle every way of writing it, so the same warning applies to it as to any HTML parsing with a regular expression.

    Example: Input: <a class="x" href="/about"> | Match: group 1: /about

  • ^[0-9A-Fa-f]{8}-(?:[0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$

    A UUID in the standard structure: 32 hexadecimal digits in five groups, separated by hyphens. The pattern checks only the structure and does not check the version.

    Example: Input: 550e8400-e29b-41d4-a716-446655440000 | Match: yes

  • ^\d{4}([ -]?)\d{4}\1\d{4}\1\d{4}$

    A structure of 16 digits in four groups, like a credit card number, with spaces, hyphens, or no separator. The backreference \1 requires the same separator throughout the number. The pattern checks only the structure: it does not check that the number is valid, and it does not suit cards of other lengths.

    Example: Input: 1234 5678 9012 3456 | Match: yes; no match in 1234-5678 9012 3456

  • ^[\p{L}\s]+$

    Text with letters in any language and spaces only, with the u flag in JavaScript and PHP. The pattern does not include digits, punctuation, or the apostrophe, so for names with an apostrophe, such as D'Arcy, add the apostrophe to the class.

    Example: Pattern: ^[\p{L}\s]+$ | Input: café crème | Match: yes; no match in café!

  • ^[A-Za-zÀ-ÖØ-öø-ÿ\s'-]+$

    A name with Latin letters, including accented ones such as ë or é, spaces, the apostrophe, and the hyphen, for example in a form name field. In PHP, add the u flag. Use it for lenient checks only, because real names sometimes contain other characters.

    Example: Input: Zoë Saint-Marie, O'Brien | Match: both

  • ^\d{1,3}(?:,\d{3})*(?:\.\d+)?$

    A number with a comma as the thousands separator and an optional decimal point. A number without separators, such as 1234, does not pass, so when both forms are allowed, remove the commas before the check.

    Example: Input: 1,234,567.89 | Match: yes; no match in 1,23

  • \B(?=(\d{3})+(?!\d))

    Adds a comma thousands separator to a whole number, by replacing with a comma with the g flag. The pattern finds positions followed by a multiple of three digits. In a decimal number, the operation also affects the part after the point, so apply it to the whole part only.

    Example: Pattern: \B(?=(\d{3})+(?!\d)) | Replacement: , | Input: 1234567 | Result: 1,234,567

  • ^-?\d+(?:\.\d+)?$

    A whole or decimal number, positive or negative, with a decimal point. A number that starts with a point, such as .5, does not pass.

    Example: Input: -12.5 | Match: yes

  • ^0+(?=\d)

    Removes leading zeros, by replacing with an empty string. The lookahead keeps at least one digit, so 000 becomes 0 and not an empty string.

    Example: Pattern: ^0+(?=\d) | Replacement: (empty) | Input: 007 | Result: 7

Using regex on the command line

  • grep -E 'error|warning' example.log

    Shows the lines that contain error or warning. The -E option turns on extended expressions (ERE), where + ? | ( ) { } work without a backslash. Wrap the pattern in single quotes so the shell does not interpret the special characters.

  • grep '[0-9]\{3\}' example.txt

    In grep without -E, and also in sed without -E, curly braces, parentheses, and the vertical bar need a backslash to get their special meaning. This syntax appears in older scripts, and for new ones grep -E is simpler.

  • grep -P '\d{3}-\d{4}' example.txt

    The -P option turns on Perl-syntax expressions, which include \d, lazy quantifiers, lookahead and lookbehind, and \K. The option exists in GNU grep, the common version on Linux, and not in every version of grep.

  • grep -oE '[0-9]+' example.txt

    The -o option shows only the matched part, each match on its own line, rather than the whole line. Used to pull numbers, addresses, and IDs out of files.

  • grep -iE 'fail(ed|ure)' example.log

    A case-insensitive search with a group of alternatives. The command finds failed, failure, FAILED, and Failure.

  • grep -wE 'id|user' example.txt

    The -w option searches for whole words only, similar to adding \b on both sides, so id does not match inside the word valid.

  • grep -vE '^[[:space:]]*(#|$)' example.conf

    Shows a configuration file without comment lines and without empty lines. The -v option inverts the selection and shows the lines that do not match.

  • grep -rnE 'TODO|FIXME' ./src

    A recursive search in all the files in a folder, with the line number and file name in every result. To limit it to a file type, add for example --include='*.php'.

  • grep -oE '\b([0-9]{1,3}\.){3}[0-9]{1,3}\b' access.log | sort | uniq -c | sort -rn | head

    Pulls all the IP addresses from a web server log file, counts how many times each address appears, and shows the ten most active addresses. Useful for finding the source of unusual load or a scan.

    Example: 1520 203.0.113.7

  • grep -E '" [45][0-9]{2} ' access.log

    Shows requests that ended with an error, a 4xx or 5xx code, in a log file in the common web server format, where the response code comes after the quotes that close the request line. For server errors only, change it to 5[0-9]{2}.

  • grep -E 'Failed password' auth.log | grep -oE 'from ([0-9]{1,3}\.){3}[0-9]{1,3}' | sort | uniq -c | sort -rn

    Counts failed SSH login attempts by IP address and shows the addresses with the most attempts first. The file name and location vary by distribution, for example auth.log or secure in the /var/log folder.

  • sed -E 's/([[:alpha:]]+) ([[:alpha:]]+)/\2 \1/' example.txt

    Swaps the first two words on every line, using groups and the \1 and \2 references in the replacement text. The -E option turns on extended expressions, and the result is shown on the screen without changing the file.

    Example: hello world -> world hello

  • sed -E 's|([0-9]{4})-([0-9]{2})-([0-9]{2})|\3/\2/\1|g' example.txt

    Converts dates from YYYY-MM-DD to DD/MM/YYYY throughout the file. The | character serves as the delimiter instead of /, so there is no need for a backslash before the slashes in the date. The g flag at the end replaces all matches on the line, not only the first.

  • sed -i.bak -E 's#http://example\.com#https://example.com#g' example.html

    Replaces addresses inside the file itself. The -i.bak option saves a copy of the original file with the .bak extension before the change, and it is best to always use it, because without a backup you cannot undo a wrong replacement.

  • sed -E '/^[[:space:]]*#/d' example.conf

    Deletes all comment lines from the output, including comments with spaces before the # sign. The d command deletes lines that match the pattern between the slashes.

  • sed -E 's/[[:space:]]+$//' example.txt

    Removes spaces and tabs from the end of every line. Useful for cleaning up code files and comparing files, where extra spaces at the end of a line cause invisible differences.

  • find . -regextype posix-extended -regex '.*\.(jpe?g|png)$'

    Finds image files with a regular expression. In find, the pattern must match the whole path, not just the file name, so it starts with .*. For a case-insensitive search, use -iregex. On macOS, the syntax is different: find -E . -regex.

  • awk '$9 ~ /^5[0-9][0-9]$/' access.log

    Shows requests with a 5xx server error code in a log file, by checking the pattern against the ninth field only. The ~ operator checks for a match, and !~ checks for no match. awk uses extended expressions, without \d.

  • awk -F'[,;]' '{print $2}' example.csv

    Splits each line into fields by a comma or a semicolon and shows the second field. In awk, the separator in the -F option can be a regular expression. The command does not handle commas inside quoted fields.

A regular expression (regex) is a text pattern that describes which strings match it, and it is used for searching, input validation, data extraction, and text replacement. The basic syntax is shared by most languages and tools, but engines differ: JavaScript, PHP, Python, and grep -P support a rich syntax, while grep -E, sed, and awk use a more limited POSIX syntax, without \d, lazy quantifiers, or lookahead and lookbehind. The patterns on this page are shown without delimiters: in JavaScript and PHP, wrap them in slashes, for example /\d+/, and add a backslash before every / inside the pattern.

You can try the patterns on sample text with our Regex tester before you put them in code or a script.

The ready-made patterns are simplified on purpose and suit a first check of the input structure. They do not replace a full check in code, such as an ID number check digit or a date that exists in the calendar, and it is best not to make them stricter than needed, so valid input is not rejected. When you validate user input, also limit the input length and avoid nested quantifiers, which can slow the check down a lot.

Regular expressions (regex) FAQ

What is a regular expression?

A regular expression is a text pattern that describes a set of strings, for example "three digits followed by a hyphen". It is used for advanced search, form input validation, pulling data out of files, and replacing text, and it is supported in almost every programming language, code editor, and command-line tool.

How do I validate an email address with a regular expression?

For most forms, the pattern ^[^\s@]+@[^\s@]+\.[^\s@]+$ is enough: it checks for text without spaces, @, and a domain with a dot. The page also shows a more detailed version that allows Latin letters only, but a check that is too strict can reject valid addresses.

What is the difference between a greedy and a lazy quantifier?

A greedy quantifier, such as * or +, takes as many characters as possible, and a lazy quantifier, such as *? or +?, takes as few as possible. A lazy quantifier suits cases where you want to stop at the first closing character, for example at the end of a tag or at the closing quotes.

How do I test a regular expression before using it?

The simplest way is to paste the pattern and sample text into a regex tester, which highlights the matches and shows the captured groups. Test examples that should fail as well, not only valid ones, to make sure the pattern is not too lenient.

Can regular expressions match letters in any language?

Yes. The class \p{L} matches a letter in any language, including accented letters such as é, and the range [\u00C0-\u024F] covers accented Latin letters. In PHP, add the u flag to every pattern that works with non-ASCII text, and in JavaScript, add the u flag for \p{L} and avoid \w and \b with such text, because they cover ASCII letters only.

How do I use a regular expression with grep and sed?

Write the pattern in single quotes after the -E option: grep -E shows the matching lines, and with -o only the matched part. In sed -E, the s/old/new/g form replaces all matches, and \1 inserts the content of the first group. Both tools use [0-9] instead of \d, and for the full syntax grep has the -P option.

Shopping cart

Your cart is emptyYou can start with one of our popular plans.

Site search

Accessibility

Text size
100%
Accessibility statement