Regular Expressions (Regex) Beginner's Guide

๐Ÿ“– 12 min read ยท Text & Code ยท Try Regex Tester โ†’

What is Regex?

A regular expression (regex or regexp) is a sequence of characters that defines a search pattern. Regex is used to search, match, extract, validate, and replace text. It is supported in virtually every programming language and is one of the most powerful tools in a developer's toolkit.

For example, the regex \d{3}-\d{4} matches phone number patterns like "555-1234". Once you understand the building blocks, you can write patterns to match almost any text structure.

Basic Syntax: Character Classes

PatternMatches
.Any character except newline
\dAny digit (0-9)
\DAny non-digit
\wWord character (a-z, A-Z, 0-9, _)
\WNon-word character
\sWhitespace (space, tab, newline)
\SNon-whitespace
[abc]Any of: a, b, or c
[^abc]Any character except a, b, c
[a-z]Any lowercase letter
[A-Z]Any uppercase letter
[0-9]Any digit (same as \d)

Quantifiers

QuantifierMeaning
*Zero or more times
+One or more times
?Zero or one time (optional)
{n}Exactly n times
{n,}At least n times
{n,m}Between n and m times
*? +? ??Lazy (non-greedy) versions โ€” match as few as possible

Anchors & Boundaries

^

Start of string (or line with m flag)

$

End of string (or line with m flag)

\b

Word boundary โ€” position between a word char and non-word char

\B

Non-word boundary

Groups & Alternation

(abc)

Capturing group โ€” captures the matched text for later use

(?:abc)

Non-capturing group โ€” groups without capturing

(?<name>abc)

Named capturing group โ€” access by name

a|b

Alternation โ€” matches a or b

(?=abc)

Positive lookahead โ€” matches if followed by abc

(?!abc)

Negative lookahead โ€” matches if NOT followed by abc

Practical Regex Examples

Email validation

^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$

Matches standard email addresses. Not 100% RFC-compliant but covers 99% of real emails.

URL matching

https?:\/\/[^\s/$.?#].[^\s]*

Matches http and https URLs.

Phone number (US)

^\+?1?[\s.-]?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$

Matches US phone numbers in various formats.

Strong password

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$

Requires lowercase, uppercase, digit, special char, min 8 chars.

IPv4 address

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

Validates IPv4 addresses (0.0.0.0 to 255.255.255.255).

Hex color code

^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$

Matches 3 or 6 digit hex color codes like #FFF or #FF5733.

Regex Flags

g

Global โ€” find all matches, not just the first

i

Case-insensitive โ€” match regardless of letter case

m

Multiline โ€” ^ and $ match start/end of each line

s

DotAll โ€” dot (.) matches newline characters too

u

Unicode โ€” enables full Unicode support

Test Your Regex Patterns

Write and test regex patterns with real-time match highlighting in your browser.

Regex Tester โ†’