Tham khảo Regex

Lớp Ký tự

Cú pháp Tên Mô tả Ví dụ
. Any char Matches any single character except newline .at → hat,cat,mat
\d Digit Matches any digit \d{3} → 123,456
\D Non-digit Matches any non-digit \D → a,b,!
\w Word char Letter,digit or underscore \w+ → hello_world
\W Non-word Any non-word char \W → @,#,!
\s Whitespace Space,tab,newline \s → space,tab
\S Non-whitespace Any non-whitespace \S → a,1,X
[abc] Char set Matches any char in brackets [aeiou] → a,e,i,o,u
[^abc] Negated set Matches chars NOT in brackets [^0-9] → a,b,!
[a-z] Range Matches any char in range [A-Z] → A,B,C
\n\t\r Escapes Control characters \n → newline

Lượng từ

Cú pháp Tên Mô tả Ví dụ
* 0 or more 0+ occurrences, greedy a* → "",a,aa,aaa
+ 1 or more 1+ occurrences a+ → a,aa,aaa
? Optional 0 or 1 colou?r → color,colour
{n} Exactly n Exactly n times \d{3} → 123,456
{n,} n or more n+ times \d{2,} → 12,12345
{n,m} n to m Between n and m \d{2,4} → 12,123,1234
*? Lazy star 0+, as few as possible a.*?b → ab,aXb
+? Lazy plus 1+, as few as possible a.+?b → aXb,aXYb

Neo

Cú pháp Tên Mô tả Ví dụ
^ Start Start of string/line ^Hello → Hello world
$ End End of string/line end$ → the end
\b Word boundary Between word and non-word \bcat\b → cat not catch
\B Non-boundary Not at word boundary \Bcat → location

Nhóm

Cú pháp Tên Mô tả Ví dụ
(...) Capture group Captures for backreference (ab)+ → ababab
(?:...) Non-capture Groups without capture (?:ab)+ → matches,no capture
(?=...) Lookahead Asserts what follows foo(?=bar) → foobar
(?!...) Negative lookahead Asserts what does NOT follow foo(?!bar) → food not foobar
| Alternation OR cat|dog → cat or dog
\1 Backreference Same text as group 1 (\w)\1 → aa,bb,cc

Cờ

Cú pháp Tên Mô tả Ví dụ
g Global All matches /cat/g → all matches
i Case insensitive Ignore case /cat/i → Cat,CAT,cat
m Multiline ^ and $ per line ^ and $ match each line
u Unicode Unicode support Unicode support
s Dotall dot matches newline . matches newline too

Thông dụng

Cú pháp Tên Mô tả Ví dụ
\d{3}-\d{4} Phone Phone number format 010-1234
[\w.-]+@[\w-]+\.[a-z]{2,} Email Email address [email protected]
https?://[\w.-]+ URL Web URL https://example.com
\d{4}-\d{2}-\d{2} Date YYYY-MM-DD 2024-01-15
[A-Z][a-z]+ Capitalized Capitalized words Hello,World
#[0-9a-fA-F]{6} Hex color 6-digit hex color #FF6600,#ff6600