Chuyển đến nội dung chính
eLearner.app
Mô-đun 1 · Bài học 2 trong tổng số 42/32 trong khóa học~10 min
Bài học theo mô-đun (2/4)

Các lớp cơ bản: \d \w \s

Beyond literal characters, regex give you predefined classes: shortcuts for "any digit", "any word character", "any whitespace". They are the first step toward truly useful patterns.

ClassMatches
\dA digit (0-9)
\wA word character (A-Za-z0-9_)
\sA whitespace (space, tab, newline, etc.)
\DNOT a digit
\WNOT a word character
\SNOT a whitespace

Each one matches a single character. To match "one or more characters" you need quantifiers (+, in module 2), but we will use + right away because "find me all the numbers" is too useful to wait for.

Code
Pattern: \d+
Sample:  Ho 3 mele, 12 pere e 100 prugne.
            ^      ^^      ^^^

\d+ means one or more consecutive digits: it matches 3, 12 and 100 as three separate matches (with the g flag).

\w: word characters

\w is equivalent to [A-Za-z0-9_] (ASCII letters, digits, underscore). It does NOT include accents, Greek letters or emoji: for those you need Unicode property escapes (\p{L}, module 5).

Deep dive into basic classes and negations

Predefined classes \\d, \\w, \\s speed up coding. Uppercase versions (\\D, \\W, \\S) negate the set. For instance, \\S+ captures any block of text devoid of spaces (like whole words including punctuation). The engine handles \\s by matching not only the standard space, but also tabs (\\t) and newline characters (\\n or \\r).

Try it

tập thể dục#regex.m1.l2.e1
Nỗ lực: 0Đang tải…

Extract every sequence of consecutive digits (numbers) from the text. Use the `\\d` class with the `+` quantifier.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

\\d+ captures one or more digits. With the g flag you collect every match.

Giải pháp khả dụng sau 3 lần thử

Review exercise

tập thể dục#regex.m1.l2.e2
Nỗ lực: 0Đang tải…

Find every 'word' in the text: a continuous sequence of word characters (`\\w+`).

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

\\w+ matches sequences of letters/digits/underscore. Punctuation is skipped.

Giải pháp khả dụng sau 3 lần thử

Additional challenge

tập thể dục#regex.m1.l2.e3
Nỗ lực: 0Đang tải…

Find all sequences of one or more consecutive whitespace characters in the text (including spaces, tabs, and newlines).

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Use the \s class with the + quantifier to capture consecutive whitespace sequences.

Giải pháp khả dụng sau 3 lần thử