Lesson 81 +20 XP

RegExp Patterns

RegExp Patterns

Regex patterns have special characters that match types of text.

Character classes

PatternMatches
\dany digit
\wword character (letters, digits, underscore)
\swhitespace (space, tab, newline)
. any single character
/\d/.test("abc123");  // true (has a digit)
/\d/.test("abc");     // false

Quantifiers

PatternMeaning
*zero or more
+one or more
?zero or one
{n}exactly n
{n,m}between n and m
/a+/.test("caa"); // true

Anchors

PatternMeaning
^start of text
$end of text
/^hello$/.test("hello");     // true
/^hello$/.test("say hello"); // false

Brackets

[abc] matches a, b, or c. [0-9] matches any digit.

TL;DR

  • \d digits, \w word chars, \s whitespace.
  • * + ? {n,m} control how many.
  • ^ and $ anchor to start and end.
  • [abc] matches one of the listed chars.