Online admissions open for the SEO, web development and networking & cybersecurity courses. Enquire for the next batch.

Regular Expressions (Regex) Explained with Examples

5 min read Updated By the SkillNewton team

What is a regular expression?

A regular expression (regex) is a pattern that describes a set of strings. Programs use regexes to search text, check its format, extract parts of it and replace matches. The syntax combines literal characters with special symbols for character classes, repetition, position and grouping, and it works in nearly every language, including Python, PHP and JavaScript.

Key terms: pattern, match, metacharacter and flag

  • Pattern: the regex itself, such as \d{6} for six digits.
  • Match: a part of the input text that fits the pattern.
  • Metacharacter: a character with special meaning, such as . * + ? ^ $ ( ) [ ] { } | \. Put a backslash before it to match it literally, as in \..
  • Capture group: a bracketed part of the pattern whose match you can read back separately.
  • Flag (modifier): an option that changes how matching works, such as case-insensitivity.

Regex syntax: the building blocks

SyntaxMeaningExample matches
abcLiteral characters"abc"
.Any character except a newline"a", "7", "#"
[aeiou], [^0-9]Character class; ^ inside negates ita vowel; any non-digit
\d \w \sDigit, word character (letter, digit, underscore), whitespace"5", "_", " "
* + ?Zero or more, one or more, zero or onecolou?r matches "color" and "colour"
{3}, {2,4}Exactly 3; between 2 and 4\d{4} matches "2026"
*? +?Lazy versions: match as little as possible".+?" stops at the first closing quote
^ $ \bStart, end, word boundary\bcat\b matches "cat" but not "catalogue"
( ), (?: )Capturing group; non-capturing group(\d{2})-(\d{2})
a|bAlternation: either sideERROR|WARN

Named groups make patterns readable: (?P<year>\d{4}) in Python and (?<year>\d{4}) in JavaScript. PHP accepts both forms. A backreference such as \1 matches the same text a group captured earlier, so \b(\w+) \1\b finds doubled words like "the the".

Lookarounds and flags

Lookarounds check what comes before or after a position without including it in the match. (?=...) is a positive lookahead, (?!...) a negative lookahead, (?<=...) a positive lookbehind and (?<!...) a negative lookbehind. For example, \d+(?= rupees) matches "250" in "250 rupees" but leaves out the word.

FlagPythonPHP / JavaScriptEffect
Ignore casere.IGNORECASEiUpper and lower case match each other
Multilinere.MULTILINEm^ and $ match at each line
Dot matches newlinere.DOTALLs. also matches \n
Verbosere.VERBOSEx (PHP only)Ignore whitespace and allow comments in the pattern
GlobalUse findall or finditerg (JavaScript only)Find every match, not just the first

Regex in Python, PHP and JavaScript

Python: the re module

import re

log = "2026-11-10 09:15:02 ERROR db timeout\n2026-11-10 09:16:40 WARN slow query"
line = re.compile(r"^(?P<date>\d{4}-\d{2}-\d{2}) (?P<time>[\d:]{8}) (?P<level>ERROR|WARN|INFO)", re.MULTILINE)
for m in line.finditer(log):
    print(m["date"], m["level"])                  # 2026-11-10 ERROR, then 2026-11-10 WARN

print(re.findall(r"\b\d{6}\b", "Pune 411001, Delhi 110001"))  # ['411001', '110001']
print(re.sub(r"\s+", " ", "too    many   spaces"))            # too many spaces
print(bool(re.fullmatch(r"[A-Z]{4}0[A-Z0-9]{6}", "SBIN0001234")))  # True: IFSC format

re.search() finds the first match anywhere, re.match() only at the start and re.fullmatch() only if the whole string fits, which is what you want for format checks.

PHP: preg functions

<?php
$text = 'Order #A-1042 shipped on 2026-11-08, order #B-2210 pending';

if (preg_match('/#([A-Z])-(\d+)/', $text, $m) === 1) {
    echo $m[0], ' ', $m[1], ' ', $m[2], PHP_EOL;          // #A-1042 A 1042
}

preg_match_all('/#(?<series>[A-Z])-(?<num>\d+)/', $text, $all);
echo implode(', ', $all['num']), PHP_EOL;                 // 1042, 2210

echo preg_replace('/(\d{4})-(\d{2})-(\d{2})/', '$3/$2/$1', $text), PHP_EOL;
// Order #A-1042 shipped on 08/11/2026, order #B-2210 pending

PHP patterns sit between delimiters, usually slashes, with flags after the closing one, as in /hello/i. Add the u flag when the text is UTF-8, such as Hindi or other non-ASCII input.

JavaScript: RegExp literals

const text = "Call 98765 43210 or 91234 56789";
for (const m of text.matchAll(/(\d{5}) (\d{5})/g)) {
  console.log(m[1] + m[2]);                    // 9876543210, then 9123456789
}
console.log(/^[a-z0-9_]{3,16}$/i.test("Asha_2026"));                       // true
console.log("2026-11-10".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1"));  // 10/11/2026

Catastrophic backtracking and ReDoS

Most regex engines, including those in Python, PHP (PCRE) and JavaScript, backtrack: when part of a pattern fails, they go back and try other ways to split the input. Nested quantifiers such as ^(a+)+$ give an exponential number of ways, so a string of 30 "a" characters followed by "!" can make the engine work for a very long time. Attackers can trigger this deliberately with crafted input, a denial-of-service attack known as ReDoS, which OWASP documents.

  • Avoid nested quantifiers and overlapping alternatives such as (\w|\d)+.
  • Make patterns specific: [^"]* instead of .* between quotes.
  • Limit input length before matching untrusted text.
  • Use atomic groups (?>...) or possessive quantifiers a++, available in PCRE and in Python since 3.11, to stop needless backtracking.
  • In PHP, check whether a preg_ function returned false, then read preg_last_error_msg(); hitting pcre.backtrack_limit is reported that way.

Do not validate email with an overly strict regex

Valid email addresses can contain plus signs, long new domain endings, subdomains and characters most hand-written patterns reject, so a strict regex turns away real users. A loose check catches typos; the only real proof is sending a confirmation link.

import re

def looks_like_email(value: str) -> bool:
    return re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", value) is not None

print(looks_like_email("[email protected]"))  # True
print(looks_like_email("asha@localhost"))                # False

In PHP, filter_var($email, FILTER_VALIDATE_EMAIL) is the standard check, as used in form handling. Also avoid regex for parsing HTML or JSON; use a real parser, such as the one described in working with JSON.

Practical exercise: extract data from a log file

  1. Create a text file with ten log lines in the format 2026-11-10 09:15:02 LEVEL message, mixing INFO, WARN and ERROR.
  2. Write a Python script that uses one compiled pattern with named groups to count lines per level.
  3. Print the time of every ERROR line, then use re.sub() to rewrite each date as DD/MM/YYYY.
  4. Write the same count in PHP with preg_match_all() and confirm the totals match.
  5. Test your pattern against a 10,000-character line of spaces and check that it returns quickly.

You are done when both scripts report the same counts and you can explain each part of your pattern. The PHP Foundation course uses regex for validating and processing form input.

Common mistakes

  • Forgetting to escape metacharacters, so . in a domain name matches any character.
  • Using re.match() or a pattern without anchors for format checks, so extra text after a valid part slips through.
  • Writing greedy .* where a lazy or negated class is needed, which swallows too much text.
  • Running nested-quantifier patterns on untrusted input, which risks catastrophic backtracking.
  • Rejecting real email addresses with an over-strict pattern instead of sending a confirmation link.

Frequently asked questions

Are regexes the same in every language?

The core syntax is shared, but details differ. JavaScript has no possessive quantifiers, Python names groups with (?P<name>...), and flags are written differently in each language, so test patterns in the language you will use.

How do I test a regex quickly?

Use an interactive Python session or a short script with several matching and non-matching examples. Online regex testers also help, but select the right flavour and never paste private data into them.

When should I not use a regular expression?

Avoid regex for nested formats such as HTML, JSON or code; use a parser. For simple fixed text, string methods such as startswith() or str_contains() are clearer and faster.

Want to Learn This Properly?

The PHP Web Development: Foundation & Practical Implementation (Online) turns guides like this into practised skills, with projects on real websites.

WhatsApp Call Us Now

Free counselling

Send an Enquiry

Tell us which course you are interested in. We reply by email or phone with the next batch and how to enrol.

Protected by reCAPTCHA. Google Privacy and Terms apply.

We reply by email or phone within working hours. No spam.