bytekit

Regex for Beginners: 12 Patterns You Will Actually Use

A short cheat sheet of the symbols that matter, then twelve ready-made patterns for phone numbers, PIN codes, dates, emails, URLs and more, each explained piece by piece.

By Tushar Dowerah · · 8 min read

Regular expressions have a reputation for looking like a cat walked across the keyboard. ^[6-9]\d{9}$ does not explain itself. But it reads perfectly well once you know the dozen or so symbols involved: it means “a digit from 6 to 9, followed by exactly nine more digits, and nothing else”, which is the shape of an Indian mobile number.

This guide teaches you to read and write patterns like that. It starts with a short cheat sheet, then works through twelve patterns you will genuinely use, each broken down piece by piece. Every pattern uses JavaScript syntax, which also works almost unchanged in Python, PHP, Java and most code editors.

What a regex is

A regular expression, or regex, describes a shape of text rather than exact text. Searching for cat finds those three letters. Searching for c[aou]t finds cat, cot and cut. Searching for \d{6} finds any run of six digits, such as a PIN code.

People use regex for three jobs:

  • Validation: does this form field look like a phone number?
  • Extraction: pull every date, email or order number out of a long text or log file.
  • Find and replace: reformat thousands of lines at once in your editor.
Regex TesterPaste any pattern from this guide and see every match highlighted live, with groups and a replace preview.

The cheat sheet

SymbolMeansExample
.Any single character except a new lineh.t matches hat, hot, h7t
\dA digit, 0 to 9\d\d matches 42
\wA word character: letter, digit or underscore\w+ matches user_42
\sWhitespace: space, tab or new linea\sb matches “a b”
\D \W \SThe opposite of \d, \w and \s\D matches any non-digit
[abc]One of the characters listedgr[ae]y matches grey and gray
[a-z]One character in a range[A-Z] matches one capital letter
[^abc]One character not listed[^0-9] matches any non-digit
*Zero or more of the previous itemab*c matches ac, abc, abbbc
+One or more\d+ matches 7 and 2026
?Optional: zero or onecolou?r matches color and colour
{n} {n,m}Exactly n, or between n and m\d{2,4} matches 2 to 4 digits
^ $Start and end of the text (or line, with the m flag)^Hi only matches at the start
\bA word boundary\bcat\b skips “concatenate”
a|bEither a or bjpe?g|png matches jpg, jpeg, png
( )A group you can repeat or capture(ha)+ matches hahaha
(?: )A group that is not captured(?:www\.)? optional www.
\.A literal dot (escape special characters with \)\.com matches .com

Flags change how the whole pattern behaves. The ones you will use most are g (find every match, not just the first), i (ignore upper and lower case) and m (make ^ and $ work on each line).

The one habit that prevents most bugs

Without anchors, a pattern matches if it appears anywhere in the text. That is what you want when searching, and exactly what you do not want when validating.

\d{6}      finds a PIN code inside "abc1234567xyz"   (bad for validation)
^\d{6}$    accepts only text that is six digits and nothing else

So: use ^ and $ when you check a whole value, such as a form field, and leave them out (often with \b instead) when you search inside longer text.

12 patterns you will actually use

For each pattern you get what it matches, what it rejects, and what every piece means. Copy them into the tester and try your own examples, especially ones that should fail.

1.Digits only

^\d+$

Matches: 7, 2026, 000123

Does not match: 12a, 12 34, (empty)

^
Start of the text
\d+
One or more digits
$
End of the text

Use ^\d{4,8}$ instead to also limit the length, for example to 4 to 8 digits for an OTP.

2.Indian mobile number, with optional +91

^(?:\+91[\s-]?|0)?[6-9]\d{9}$

Matches: 9876543210, +91 9876543210, +91-9876543210, 09876543210

Does not match: 5876543210, 98765 43210, +1 9876543210

(?:\+91[\s-]?|0)?
Optionally +91 with an optional space or hyphen, or a leading 0
\+
A literal plus sign. A bare + would mean “one or more”
[6-9]
Indian mobile numbers start with 6, 7, 8 or 9
\d{9}
Exactly nine more digits

It is usually kinder to remove spaces from what the user typed first, with value.replace(/\s/g, ""), than to make the pattern accept every possible format.

3.Indian PIN code

^[1-9]\d{5}$

Matches: 786001, 110001, 560034

Does not match: 012345, 78600, 7860011

[1-9]
The first digit is a region from 1 to 9, never 0
\d{5}
Five more digits, six in total

4.A practical email check

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

Matches: ana@example.com, first.last+news@mail.co.in

Does not match: ana@example, ana @example.com, ana@@example.com

[^\s@]+
One or more characters that are not a space or @
@
Exactly one @ sign
[^\s@]+\.[^\s@]+
A domain with at least one dot

Deliberately simple. The official rules for email addresses are so complex that a “perfect” regex is thousands of characters long and still cannot tell whether the inbox exists. Catch obvious typos with this, then send a confirmation email.

5.Date in YYYY-MM-DD format

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

Matches: 2026-11-27, 1999-01-01

Does not match: 2026-13-01, 2026-11-32, 27-11-2026

\d{4}
A four-digit year
(0[1-9]|1[0-2])
A month from 01 to 12
(0[1-9]|[12]\d|3[01])
A day from 01 to 31

Regex checks the shape, not the calendar, so 2026-02-31 still passes. Check real dates with your language’s date library. For Indian style dates, swap the order: ^(0[1-9]|[12]\d|3[01])/(0[1-9]|1[0-2])/\d{4}$ matches 27/11/2026.

6.24-hour time

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

Matches: 09:30, 18:05, 23:59

Does not match: 24:00, 9:30, 12:60

([01]\d|2[0-3])
Hours 00 to 19, or 20 to 23
:
A literal colon
[0-5]\d
Minutes 00 to 59

7.Hex colour code

^#(?:[0-9a-fA-F]{3}){1,2}$

Matches: #fff, #2E6A4C, #6cc49a

Does not match: #ffff, 2e6a4c, #ggg

#
A literal hash
[0-9a-fA-F]{3}
Three hex digits
(?: ){1,2}
That group once or twice: 3 or 6 digits in total

Add the i flag and you can shorten the class to [0-9a-f]. To also allow 4 and 8 digit colours with transparency, use ^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$ with the i flag.

8.Find web links in text

https?://[^\s<>"]+[^\s<>".,;:!?)]   flags: g

Matches: https://bytekit.online, http://example.com/a?b=1

https?://
http:// or https://
[^\s<>"]+
Everything up to the next space, angle bracket or quote
[^\s<>".,;:!?)]
The last character must not be punctuation, so a full stop after a link is left out

In JavaScript code, a pattern written between slashes must escape its own slashes: /https?:\/\/[^\s<>"]+[^\s<>".,;:!?)]/g. The tester adds the slashes for you, so type the pattern without them.

9.Collapse repeated spaces

[ \t]{2,}   flags: g

Matches: the gap, tabs and spaces

[ \t]
A space or a tab
{2,}
Two or more in a row

Replace every match with a single space. To trim the start and end of each line as well, use ^[ \t]+|[ \t]+$ with the g and m flags and replace with nothing.

10.Find accidentally doubled words

\b(\w+)\s+\1\b   flags: gi

Matches: the the, is is, The the

Does not match: the theme

\b(\w+)
A whole word, captured as group 1
\s+
One or more spaces or new lines
\1\b
The same word again, as a whole word. \1 is a backreference to group 1

Replace with $1 to keep one copy. A favourite of editors and proofreaders.

11.Password rule: 12+ characters with upper, lower and a digit

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{12,}$

Matches: Correct7horse, sunnyDay2026x

Does not match: short1A, alllowercase123

(?=.*[a-z])
A lookahead: somewhere ahead there is a lowercase letter. It checks without moving forward
(?=.*[A-Z])
…and an uppercase letter
(?=.*\d)
…and a digit
.{12,}
Then the whole value must be at least 12 characters

Lookaheads are the standard way to check several rules at once. That said, length is what really makes a password strong. See our guide on creating strong passwords you can remember.

12.PAN and IFSC codes

^[A-Z]{5}\d{4}[A-Z]$

Matches: ABCDE1234F

Does not match: ABCD1234F, abcde1234f

[A-Z]{5}
Five capital letters
\d{4}
Four digits
[A-Z]
One final capital letter

A bank IFSC code is four letters, a zero, then six letters or digits: ^[A-Z]{4}0[A-Z0-9]{6}$ matches SBIN0001234. Convert the input to upper case first instead of adding the i flag, so you store a clean value. These check the format only, not whether the PAN or branch exists.

Greedy and lazy matching

The repeaters * and + are greedy: they grab as much text as they can. That surprises everyone at least once.

Text:     <b>bold</b> and <b>more</b>
Pattern:  <b>.*</b>     matches the whole line, from the first <b> to the last </b>
Pattern:  <b>.*?</b>    matches <b>bold</b> and then <b>more</b> separately

Adding ? after a repeater makes it lazy, taking as little as possible. An often better option is to say exactly what may appear, such as <b>[^<]*</b>, which is both clearer and faster.

When not to use regex

  • HTML, XML and JSON. These formats nest, and regex cannot reliably track nesting. Use a real parser, such as DOMParser or JSON.parse.
  • Real-world validity. A regex can say a value looks like a date, PAN or email. Only a calendar, a database or a confirmation email can say it is real.
  • Comparing two texts. To find what changed between two versions of a file, use a diff tool rather than trying to match lines by hand.
  • Unreadable one-liners. If a pattern needs a paragraph to explain, split it into steps in code. Your future self will thank you.
Text Diff CheckerCompare two versions of a text side by side, after a find and replace, to check exactly what changed.

Start with the cheat sheet, anchor your validation patterns, and test against examples that should fail. That alone puts you ahead of most of the regex found in production code.

Written by Tushar Dowerah

Independent software developer from Dibrugarh, Assam, India, coding since 2020 and building ByteKit’s free, private tools. Spotted a mistake or have a question? Send a message.

Keep reading

All posts