Lesson 63 - Regular Expressions: Character Classes and Special Characters
In this lesson, we'll explore character classes and special characters in regular expressions, which allow you to match specific types of characters efficiently.
Understanding Character Classes
Character classes help match specific types of characters instead of exact text.
Character Class | Description | Example Pattern | Matches |
---|---|---|---|
\d |
Any digit (0-9) | /\d/ |
"abc123" ? 1 |
\w |
Any word character (a-z, A-Z, 0-9, _) | /\w/ |
"Hello_42" ? H |
\s |
Any whitespace (space, tab, newline) | /\s/ |
"Hello World" ? " " |
. |
Any single character (except newline) | /./ |
"cat" ? c |
Example:
const text = "My number is 42!";
const pattern = /\d/;
console.log(text.match(pattern)); // Output: ["4"]
Using Ranges in Character Classes
[a-z]
? Any lowercase letter[A-Z]
? Any uppercase letter[0-9]
? Any digit[aeiou]
? Any vowel-
[^a-z]
? NOT a lowercase letterExample:
const pattern = /[0-9]+/; console.log("Order 325".match(pattern)); // Output: ["325"]
Try Your Hand
- Write a regex to find all vowel letters in
"Javascript is fun!"
. - Create a regex to match any three-letter word in
"The cat sat on the mat."
.