Regex 文字 クラス リファレンス
Predefined 文字 クラス, custom ranges, および shorthand escapes で regular expressions.
Shorthand Classes
Regular expressions provide shorthand escapes for common character sets. The lowercase escapes match character classes while the uppercase escapes match their complements. These shorthands are affected by the Unicode and case-insensitive flags, expanding or contracting their membership. Using shorthands instead of explicit ranges improves readability and handles locale-specific characters correctly.
- \d
- Digit, equivalent to [0-9]
- \w
- Word char: letter, digit, underscore
- \s
- Whitespace: space, tab, newline
- \D \W \S
- Complements of the above
- .
- Any char except newline (unless dotall)
\d+ matches 123 \w+ matches foo_bar \s+ matches spaces \D matches non-digits a.b matches aXb Custom Ranges
Square brackets define a custom character class containing any of the listed characters or ranges. A hyphen between two characters creates a range based on code point order. The caret at the start negates the class. Ranges should be used carefully with Unicode because code point order does not reflect natural language order. Escaping metacharacters inside a class is simpler than outside: only the closing bracket, backslash, and caret at start need escaping.
Unicode Effects
The Unicode flag u changes how shorthands and ranges behave. With the flag, \w matches all Unicode word characters including letters from non-Latin scripts, not just ASCII. Ranges like a-z still only cover the specified code points, but the flag enables surrogate pair handling. The v flag adds set operations to character classes, allowing subtraction and intersection. Always specify the intended flag to avoid surprising matches on international text.