Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Regex Documentation

Regular expressions — classes, quantifiers, groups, lookarounds, flags and ready patterns for Indian formats.

A regular expression is a pattern that matches text. Use it to validate input (emails, phone numbers, passwords), search logs and code, extract parts of strings and find & replace. The syntax is almost the same in JavaScript, Python, Java, grep and editors like VS Code. Examples below use JavaScript, with Python and Java notes.

1. Basics & Literal Characters

Most characters match themselves: /cat/ finds "cat" in "concatenate".

/cat/.test("concatenate");          // true
"I love cats".match(/cat/)[0];      // "cat"

These metacharacters have special meaning and must be escaped with \ to match literally:

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

/1\.5/ matches "1.5"; /1.5/ also matches "125" because . means "any character".

Try patterns live at regex101.com (pick the flavour: ECMAScript, Python, Java).

2. Character Classes

Pattern Matches
. any character except a newline
\d digit [0-9]
\D not a digit
\w word character [A-Za-z0-9_]
\W not a word character
\s whitespace (space, tab, newline)
\S not whitespace
[abc] a, b or c
[^abc] anything except a, b, c
[a-z], [A-Z0-9] ranges
[.\-] a dot or a hyphen (escape - or put it first/last)
"Room 42B".match(/\d+/)[0];          // "42"
"a1-b2_c3".replace(/\W/g, "");       // "a1b2_c3"

3. Quantifiers

Quantifier Meaning
* 0 or more
+ 1 or more
? 0 or 1 (optional)
{n} exactly n
{n,} n or more
{n,m} between n and m
/colou?r/.test("color");             // true — "u" optional
/^\d{6}$/.test("110001");            // true — 6-digit PIN code
/^[a-z]{3,8}$/.test("codify");       // true

Greedy vs lazy: quantifiers grab as much as possible; add ? to take as little as possible.

"<b>bold</b><i>it</i>".match(/<.+>/)[0];     // "<b>bold</b><i>it</i>"  (greedy)
"<b>bold</b><i>it</i>".match(/<.+?>/)[0];    // "<b>"                   (lazy)

4. Anchors & Boundaries

Pattern Meaning
^ start of the string (of each line with the m flag)
$ end of the string (of each line with m)
\b word boundary
\B not a word boundary
/^\d+$/.test("123");                 // true — only digits
/^\d+$/.test("123abc");              // false
"cat scatter".match(/\bcat\b/g);     // ["cat"] — whole word only

⚠️ Without ^…$, validation passes if the pattern appears anywhere: /\d{10}/.test("abc9876543210xyz") is true.

5. Groups, Alternation & Backreferences

Pattern Meaning
(abc) capturing group
(?:abc) non-capturing group (grouping only)
(?<name>abc) named group
a|b a or b
\1, \k<name> match the same text as group 1 / the named group again
const m = "2026-10-27".match(/^(\d{4})-(\d{2})-(\d{2})$/);
m[1]; m[2]; m[3];                     // "2026", "10", "27"

const { year, month } = "2026-10-27".match(/(?<year>\d{4})-(?<month>\d{2})/).groups;

/^(cat|dog)s?$/.test("dogs");         // true
/\b(\w+) \1\b/.test("this is is a typo");   // true — repeated word

6. Lookahead & Lookbehind

Check what comes before/after without including it in the match:

Pattern Meaning
X(?=Y) X followed by Y
X(?!Y) X not followed by Y
(?<=Y)X X preceded by Y
(?<!Y)X X not preceded by Y
"Price: ₹499".match(/(?<=₹)\d+/)[0];          // "499"
"file.js file.ts".match(/\w+(?=\.ts)/)[0];      // "file"

// strong password: 8+ chars, lower, upper, digit, special
const strong = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\w\s]).{8,}$/;
strong.test("Codify@2026");                    // true
strong.test("codify2026");                     // false

7. Flags

Flag Meaning
g global — find all matches
i case-insensitive
m multiline — ^/$ match at each line
s dotAll — . also matches newlines
u Unicode — correct handling of emoji / \p{…} classes
y sticky — match only at lastIndex
"Java JAVA java".match(/java/gi);              // ["Java", "JAVA", "java"]
/^\p{Lu}/u.test("Élan");                       // true — any uppercase letter (Unicode)

8. Using Regex in JavaScript

const re = /\b\d{10}\b/g;

re.test(str);                       // true / false
str.match(/\d+/);                   // first match + groups (or null)
str.match(/\d+/g);                  // array of all matches (no groups)
[...str.matchAll(/(\w+)@(\w+)\.com/g)].map((m) => m[2]);   // all matches with groups
str.replace(/\s+/g, " ");           // collapse whitespace
str.replace(/(\w+)\s(\w+)/, "$2 $1");          // swap two words
str.replace(/\d+/g, (n) => n * 2);             // function replacement
str.split(/[,;]\s*/);               // split on comma or semicolon
str.search(/\d/);                   // index of first match or -1

const dynamic = new RegExp(`^${escapeRegex(userInput)}`, "i");
const escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");

⚠️ A regex with the g flag remembers lastIndex, so calling .test() repeatedly on the same object can alternate true/false. Don't reuse global regexes for test().

9. Python & Java

Python (re module — use raw strings r"..." so backslashes stay):

import re
re.search(r"\d+", "Room 42B").group()            # '42'
re.findall(r"[\w.+-]+@[\w-]+\.[\w.]+", text)      # all emails
re.sub(r"\s+", " ", text)                         # replace
re.split(r"[,;]\s*", "a, b;c")                     # ['a', 'b', 'c']
m = re.fullmatch(r"(\d{4})-(\d{2})-(\d{2})", "2026-10-27")
m.groups()                                        # ('2026', '10', '27')
pattern = re.compile(r"^[A-Z]{5}\d{4}[A-Z]$")     # PAN format, compiled once
re.IGNORECASE, re.MULTILINE, re.DOTALL             # flags

Java (java.util.regex — double the backslashes in string literals):

Pattern p = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})");
Matcher m = p.matcher("Due 2026-10-27");
if (m.find()) System.out.println(m.group(1));     // 2026
"a1b22c333".replaceAll("\\d+", "#");             // "a#b#c#"
"9876543210".matches("\\d{10}");                  // true — whole string
"a, b;c".split("[,;]\\s*");

10. Common Patterns

Use Pattern Notes
Email (practical) ^[\w.+-]+@[\w-]+(\.[\w-]+)+$ real validation = send a confirmation email
Indian mobile ^(?:\+91[\s-]?)?[6-9]\d{9}$ optional +91, starts with 6–9
PIN code ^[1-9]\d{5}$ 6 digits, not starting with 0
PAN ^[A-Z]{5}\d{4}[A-Z]$ e.g. ABCDE1234F
IFSC ^[A-Z]{4}0[A-Z0-9]{6}$ 11 characters, 5th is 0
GSTIN ^\d{2}[A-Z]{5}\d{4}[A-Z][1-9A-Z]Z[0-9A-Z]$ 15 characters
Username ^[a-zA-Z0-9_]{3,20}$
Strong password ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\w\s]).{8,}$
URL (simple) ^https?:\/\/[\w.-]+(?:\.[a-z]{2,})(?:[\/?#]\S*)?$ use new URL() for real parsing
Date YYYY-MM-DD ^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$ doesn't check 31 Feb
Time 24h HH:MM ^([01]\d|2[0-3]):[0-5]\d$
Hex colour ^#(?:[0-9a-fA-F]{3}){1,2}$ #fff or #ffffff
IPv4 ^((25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(25[0-5]|2[0-4]\d|1?\d?\d)$ 0–255 per part
Slug ^[a-z0-9]+(?:-[a-z0-9]+)*$ my-first-post
Trim spaces ^\s+|\s+$ (replace with "") or str.trim()
HTML tags (strip) <[^>]+> never parse HTML with regex

(In the table \| is just an escaped | for Markdown — write | in code.)

Performance & safety: nested quantifiers like (a+)+$ can take exponential time on some inputs (ReDoS). Avoid them in patterns applied to user input, limit input length, and prefer specific classes ([^"]*) over .*.

11. Cheat Sheet & References

Characters

. any   \d digit   \w word   \s space
\D \W \S  = the opposites
[abc] one of   [^abc] none of   [a-z0-9] ranges
\. \* \? \( \)  escaped literals

Quantifiers and anchors

* 0+   + 1+   ? 0-1   {n} {n,} {n,m}
*? +? ??  lazy versions
^ start   $ end   \b word boundary

Groups and lookaround

(x) capture   (?:x) group only   (?<name>x) named
a|b either   \1 backreference
x(?=y) followed by   x(?!y) not followed by
(?<=y)x preceded by   (?<!y)x not preceded by

JavaScript methods

re.test(s)
s.match(re); s.match(/x/g); [...s.matchAll(/x/g)]
s.replace(/x/g, "y"); s.replace(re, (m) => m.toUpperCase())
s.split(/[,;]\s*/)
new RegExp("^" + text + "$", "i")

Ready patterns

/^\d{6}$/                          // 6-digit PIN
/^(?:\+91)?[6-9]\d{9}$/            // Indian mobile
/^[\w.+-]+@[\w-]+(\.[\w-]+)+$/     // email (basic)
/^[A-Z]{5}\d{4}[A-Z]$/             // PAN
/^#(?:[0-9a-f]{3}){1,2}$/i         // hex colour
/^[a-z0-9]+(?:-[a-z0-9]+)*$/       // slug

References