Lesson 65 - Character Classes in Regular Expressions
Character classes in regular expressions allow you to match specific sets of characters. They provide a way to define which characters should be matched.
Common Character Classes
Character Class | Meaning | Example | Matches |
---|---|---|---|
\d |
Matches any digit (0-9) | /\d+/ |
"123" in "abc123" |
\D |
Matches any non-digit | /\D+/ |
"abc" in "abc123" |
\w |
Matches any word character (letters, digits, underscore) | /\w+/ |
"hello_123" |
\W |
Matches any non-word character | /\W+/ |
"!" , "@#" , etc. |
\s |
Matches any whitespace (space, tab, newline) | /\s+/ |
" " in "hello world" |
\S |
Matches any non-whitespace character | /\S+/ |
"hello" in "hello world" |
Example 1: Matching Digits
let text = "My age is 25.";
let result = text.match(/\d+/g);
console.log(result); // Output: ["25"]
Example 2: Extracting Words
let text = "Coding is fun!";
let words = text.match(/\w+/g);
console.log(words); // Output: ["Coding", "is", "fun"]
Example 3: Identifying Non-Alphanumeric Characters
let text = "Hello, World!";
let specialChars = text.match(/\W+/g);
console.log(specialChars); // Output: [", ", "!"]
Try Your Hand
Steps:
-
Create a File:
- Name it
lesson65-character-classes.html
.
- Name it
-
Write the Code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lesson 65 - Character Classes</title> </head> <body> <h2>Character Classes Demo</h2> <p id="output"></p> <script> let text = "Contact me at info@example.com or call 555-1234."; let matches = text.match(/\d+/g); // Extracts numbers document.getElementById("output").textContent = "Numbers found: " + matches.join(", "); </script> </body> </html>
-
Save the File.
-
Open it in a Browser to See Extracted Numbers.
Experiment
- Extract all words from a given sentence.
- Find all non-word characters in a string.
- Identify whitespace characters in a text.
Key Takeaways
- Character classes provide powerful shortcuts for matching groups of characters.
\d
,\w
,\s
, and their uppercase versions have opposite meanings.- Useful for validations and text processing.