Look at a suitcase lock with number wheels. Each wheel can show only one character, and the choices are only 0 to 9. A four-wheel lock means four positions, one digit in each.
A regex has wheels like that, called a character class: a list of the characters allowed in one position, written inside square brackets. [0-9] means "one digit, 0 to 9", and the four-wheel lock is [0-9][0-9][0-9][0-9].
One class, one character
Guess first, before you read the comments: does "$85.00".match(/[0-9]/g) give ['85', '00'], or four separate digits?
console.log("$85.00".match(/[0-9]/g)); // ['8', '5', '0', '0']
console.log(chat.match(/07[0-9][0-9]/g)); // ['0770', '0770']
[0-9]matches one character, whichever digit it is. Withg, each digit is a result of its own. So the result is four separate digits, not85and00.07[0-9][0-9]matches07followed by any two digits: the start of Dina's number07700-900-123and of Sari's number07700900461.[aeiou]matches one vowel. The order of the list doesn't matter:[aeiou]is the same as[uoiea].
Ranges and combinations
A - between two characters makes a range:
[0-9]digits,[a-z]lowercase letters,[A-Z]uppercase letters.- Ranges can be combined in one class:
[A-Za-z0-9]means one uppercase letter, lowercase letter or digit. - A range follows the order of character codes, so the left end has to be the smaller one.
[a-Z]is rejected:Invalid regular expression: /[a-Z]/: Range out of order in character class.
Negation: [^...]
A ^ right after [ turns the list around: any one character other than the ones listed.
console.log("$85.00".match(/[^0-9]/g)); // ['$', '.']
[^0-9] also matches spaces and line breaks, since those aren't digits either. ^ only negates in the first position: [0-9^] means a digit or the ^ sign.
Shorthands: \d, \w, \s
The three most used classes have shorthands:
console.log("$85.00".match(/\d/g)); // ['8', '5', '0', '0']
console.log("$85.00".match(/\D/g)); // ['$', '.']
\d(digit) is the same as[0-9].\w(word) is the same as[A-Za-z0-9_]: letters, digits and underscore.\s(space) matches a space, a tab and a line break, and other spaces too, such as\rand the non-breaking space (NBSP, which often comes along when you copy from WhatsApp or Word):/\s/.test("\u00a0")givestrue.- An uppercase letter means the opposite:
\Deverything except a digit,\Wnot a letter/digit/underscore,\Snot a space.
\d only knows the ASCII digits 0 to 9. /\d/.test("٣") (an Arabic digit) and /\d/.test("1") (a full-width digit) are both false.
Metacharacters inside square brackets
Inside [...], most metacharacters become ordinary characters. [.,] means a dot or a comma, not "any character":
console.log("$1,250.00".match(/[.,]/g)); // [',', '.']
Only four still mean something special inside square brackets: ] closes the list, \ escapes, ^ in the first position negates, and - between two characters makes a range. Want a plain -? Put it at the end: [0-9-] means a digit or a dash.
Checking the whole text: +, {n}, ^ and $
One class is one character. For validating input, meet these four signs now (the details come in the next two lessons):
+after a class: one or more characters from the list, in a row.{4}after a class: exactly 4 characters.^at the start of the pattern (outside square brackets): from the start of the text.$at the end of the pattern: up to the end of the text.
console.log("$85.00".match(/[0-9]+/g)); // ['85', '00']
console.log("$85.00".match(/[0-9.]+/g)); // ['85.00']
console.log("abc123".match(/[a-z]+/g)); // ['abc']
const validCode = /^PO-[0-9]{4}$/;
console.log(validCode.test("PO-0413")); // true
console.log(validCode.test("Code PO-0413")); // false: text before PO
console.log(validCode.test("PO-04133")); // false: 5 digits
console.log(/[0-9]/.test("Code PO-0413")); // true: one digit is enough
- Without
^and$,test()is happy to find a matching piece anywhere. For "it holds only this", put both on. +needs at least one character, so the empty text""doesn't pass/^[0-9]+$/.- Two lengths are valid, say a code of 4 or 6 digits? Combine two checks with
||:/^PO-[0-9]{4}$/.test(code) || /^PO-[0-9]{6}$/.test(code).
⚠️ What people get wrong about square brackets
- Thinking a class takes many characters.
[0-9]is one character. Need a whole number?[0-9]+. - Forgetting
^and$when validating./[A-Za-z0-9]+/.test("Hello 123")givestrue, becauseHelloalone already matches./^[A-Za-z0-9]+$/answersfalse. [A-z]looks like every letter. BetweenZandasit[ \ ] ^ _and the backtick, so they all get in. Write[A-Za-z].\din a string.new RegExp("\d")becomes/d/, which looks for the letter d. In a string, write"\\d".
TL;DR: [...] matches one character from the list. - makes a range ([0-9], [a-z], [A-Za-z0-9]), ^ in the first position turns the list around ([^0-9]), and inside square brackets . and most metacharacters are ordinary. \d = [0-9] (ASCII digits only), \w = [A-Za-z0-9_], \s = space, tab, line break; their uppercase forms are the opposite (\D = not a digit). For validation: + one or more, {n} exactly n, ^ and $ lock the start and end of the text, and || combines two patterns.
⚡ One class, one character
Write:
console.log("$85.00".match(/[0-9]/g));
Guess first: does this print ['85', '00'], or four separate digits?
Four separate digits. [0-9] matches one character, whichever digit it is, and with g each digit is a result of its own. For a whole number, add +: [0-9]+.
Meaning: Square brackets list the characters allowed in one position. - makes a range ([a-z]), and ^ right after [ turns the list around: [^0-9] is anything but a digit.
⚡ \d and \D
Write:
console.log("$85.00".match(/\d/g)); // ['8', '5', '0', '0']
console.log("$85.00".match(/\D/g)); // ['$', '.']
Meaning: \d is a digit, the same as [0-9]. Its uppercase form \D is anything except a digit. \w is a letter, digit or underscore, \s a space; \W and \S are their opposites.
⚡ Check the whole text
Write:
const validCode = /^PO-[0-9]{4}$/;
console.log(validCode.test("Code PO-0413")); // false: text before PO
Meaning: Without ^ and $, one matching piece anywhere is enough for true. {4} asks for exactly 4, + for one or more.