Module lessons (2/4)
Basic classes: \d \w \s
Writing literal patterns isn't enough when values vary (prices, user IDs, irregular whitespace). Regexes offer six predefined classes in lowercase/uppercase pairs: each class represents a single character belonging to (or complementary to) a specific category.
Mental model: positive and negative pairs
| Class | What matcha (1 character) | Explicit equivalent | Typical use with + |
|---|---|---|---|
\d | One decimal place | [0-9] | \d+ extracts integers |
\D | Any NON-digit | [^0-9] | \D+ skip alphabet/symbol blocks |
\w | ASCII word character | [A-Za-z0-9_] | \w+ extracts identifiers and tokens |
\W | Any NON-word | [^A-Za-z0-9_] | \W+ finds punctuation and separators |
\s | Whitespace, tab \t, newline \n | [\t\n\v\f\r ] | \s+ normalizes multiple spaces |
\S | Any NON-space character | [^\s] | \S+ isolate blocks separated by spaces (e.g. URL) |
Progressive examples
1. Difference between single class \d and sequence \d+
Pattern: \d+
Sample: Ho 3 mele, 12 pere e 100 prugne.
^ ^^ ^^^Without the +, \d matcha 1, 2, 1, 0, 0 as detached digits. With + he groups them into 3, 12 and 100.
2. Split non-space token with \S+ in JavaScript
const endpointLog = 'GET /api/v2/users\t200';
const columns = endpointLog.match(/\S+/g);
console.log(columns); // ['GET', '/api/v2/users', '200']3. Separate numeric and non-numeric parts with \D+
Pattern: \D+
Sample: ORD-2026-88
^^^^ ^4. Display \d, \w and boundaries on the character ribbon
Guided laboratory
Extract integer sequences with d+
Extract all sequences of consecutive digits (whole numbers) from the text. Use the \d class with +.
Show hint
Add the + quantifier after \d with the g flag enabled.
Solution available after 3 attempts
Tokenize alphanumeric words with w+
Find any continuous word/identifier in the text using \w+.
Show hint
Use \w+ to collect letters, digits and underscores while skipping punctuation.
Solution available after 3 attempts
Compact irregularly spaced blocks
Find all sequences of one or more consecutive spaces (spaces, tabs \t, and newlines \n) using \s+.
Show hint
Use the \s class with + to capture entire blocks of whitespace as a single match.
Solution available after 3 attempts
Check for understanding
What matches does 'user_01: città!'.match(/\w+/g) produce in JavaScript?
You must extract each full space-separated URL from 'Ping https://a.dev/v1?x=1 ora' (excluding 'Ping' and 'ora'). Which character class captures the https://a.dev/v1?x=1 part without stopping at : or /?