Intermediate · Map, Set, iterators, generators and regular expressions · topic 34 of 61 · 30 min
Regular expressions: the basics
Explanation
Why regular expressions?
Many text jobs are about patterns, not exact words: "is this a 6-digit PIN code?", "find all amounts like ₹1,499", "remove extra spaces". You could write loops checking each character, but a regex describes the pattern in one short line. Every major language supports them with very similar syntax, so what you learn here works almost everywhere.
Writing a regex
const pin = /^[1-9][0-9]{5}$/; // a literal between slashes
const word = new RegExp('chai', 'i'); // from a string (useful when the pattern is built at run time)
console.log(pin.test('560001')); // true
console.log(pin.test('060001')); // false (Indian PINs do not start with 0)
console.log(word.test('Masala CHAI')); // true (i flag: ignore case)The building blocks
| Pattern | Matches |
|---|---|
| abc | the exact text abc |
| . | any one character except a new line |
| \d \w \s | a digit / a word character (letter, digit, _) / a space, tab or new line |
| \D \W \S | NOT a digit / word character / space |
| [aeiou] | one of these characters |
| [0-9] [a-z] | one character in the range |
| [^0-9] | one character NOT in the set |
| ^ $ | start / end of the text (anchors) |
| a|b | a or b |
Quantifiers: how many times
| Quantifier | Meaning | Example |
|---|---|---|
| * | 0 or more | ab*c matches ac, abc, abbc |
| + | 1 or more | \d+ matches 7 or 2026 |
| ? | 0 or 1 (optional) | colou?r matches color and colour |
| {n} | exactly n | \d{6} six digits |
| {n,m} | between n and m | \d{2,4} |
Anchors matter for validation
const sixDigits = /\d{6}/;
console.log(sixDigits.test('PIN 5600019999')); // true: it FOUND six digits somewhere
const exactlySix = /^\d{6}$/;
console.log(exactlySix.test('5600019999')); // false: the whole text must be six digitsFlags
Flags come after the closing slash. g (global) finds all matches instead of the first; i ignores upper/lower case; m makes ^ and $ work on every line; u turns on full Unicode support. You can combine them: /chai/gi.
Using regex with strings
const text = 'Paid ₹250 for tea, ₹1200 for lunch';
console.log(/\d+/.test(text)); // true
console.log(text.match(/\d+/)); // ['250', index: 6, …] (first match with details)
console.log(text.match(/\d+/g)); // ['250', '1200'] (all matches)
console.log(text.replace(/\d+/g, 'XX')); // 'Paid ₹XX for tea, ₹XX for lunch'
console.log('a, b ,c'.split(/\s*,\s*/)); // ['a', 'b', 'c']Real Indian validations
const mobile = /^[6-9]\d{9}$/; // 10 digits, starting 6–9
const pinCode = /^[1-9][0-9]{5}$/; // 6 digits, not starting with 0
const ifsc = /^[A-Z]{4}0[A-Z0-9]{6}$/; // e.g. SBIN0001234: 4 letters, 0, 6 letters/digits
console.log(mobile.test('9876543210'), pinCode.test('110001'), ifsc.test('SBIN0001234')); // true true trueNeed help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Regular expressions: the basics · 1/7
In this lesson you will describe text patterns with regular expressions.
Prefer a video by a teacher? Find free videos on “javascript regular expressions tutorial for beginners” on YouTube ↗
In real life: Validating a KYC form
A fintech app collects mobile number, PIN code and bank IFSC during sign-up. Each field is checked with a regex on the phone before sending, which gives instant feedback. The server checks again, because browser checks can be bypassed.
const rules = { mobile: /^[6-9]\d{9}$/, pin: /^[1-9]\d{5}$/, ifsc: /^[A-Z]{4}0[A-Z0-9]{6}$/ };
const form = { mobile: '9123456789', pin: '0400012', ifsc: 'HDFC0001234' };
const errors = Object.keys(rules).filter((field) => !rules[field].test(form[field]));
console.log(errors); // ['pin']Practice (0/3 done)
Write isValidPin(text) that returns true only for a 6-digit Indian PIN code that does not start with 0.
Write isValidMobile(text) for Indian mobile numbers: optionally starting with "+91" or "0", then 10 digits where the first is 6, 7, 8 or 9. Spaces are not allowed.
Write extractAmounts(text) that returns all whole-number amounts written after "Rs" or "₹" (with an optional space), as numbers. "Paid Rs 250 and ₹1200, tip Rs40" gives [250, 1200, 40].
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Regular expressions in practiceMap, Set, iterators, generators and regular expressions · same module
- Iterators and the iteration protocolMap, Set, iterators, generators and regular expressions · same module
- JSON and regular expressionsPython Programming · Errors, modules and the standard library
- Validating inputBackend Development · APIs and request handling
- Built-in form validationFrontend Web Development · Forms, semantic HTML and accessibility
- Strings in depthJava Programming (Core to Spring Boot) · Arrays and strings
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What does \d+ match?
Answer: One or more digits
+ means one or more of the thing before it.
Why does /\d{6}/.test('abc560001xyz') return true?
Answer: Without ^ and $ the pattern can match anywhere in the text
Unanchored patterns find a match anywhere.
What does 'a1b22c333'.match(/\d+/g) give?
Answer: ['1', '22', '333']
With g, match returns every run of digits.
Which flag makes a regex ignore upper/lower case?
Answer: i
i stands for case-insensitive.
Why write regex patterns as raw strings like r"..."?Related
Answer: So Python passes every backslash to re unchanged
In normal strings some backslash pairs have special meanings, like \b for backspace. A raw string keeps them as written.
What do ^ and $ do in a regex?Related
Answer: Mark the start and the end of the text
Anchors make the whole text match, not just a piece of it.
From Validating input
What is 'ab12'.match(/([a-z]+)(\d+)/)[2]?Related
What does pattern="[0-9]{6}" accept?Related
Answer: Exactly six digits
[0-9] is one digit and {6} means exactly six, and the pattern must match the whole value.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 1 more topic in “Map, Set, iterators, generators and regular expressions” before its exam: Regular expressions in practice.
- Module 7 exam: Collections, iterators and regular expressions · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Asynchronous JavaScript. 61 topics left in the course before the final exam.