๐ง What is \w in Regex?
In regular expressions, \w is a shorthand character class that matches any word character.
โ
\w matches:
- Uppercase letters:
A-Z - Lowercase letters:
a-z - Digits:
0-9 - Underscore:
_
Equivalent to:
csharp
[A-Za-z0-9_]
๐ Common Patterns with \w
PatternMeaningExample Match\wA single word charactera, Z, 9, _\w+One or more word charactershello, abc123\w*Zero or more word characters"", test\w{3}Exactly 3 word charactersabc, 123^\w+$Entire string is only word charactersValid_123
โ What \w does not match:
- Spaces:
" " - Punctuation:
. , ! @ # $ % ... - Special characters:
*, +, =, /, etc.
๐งช Examples in Action
Java
java
String input = "Hello_123";
boolean matches = input.matches("\\w+"); // true
Python
python
import re
re.match(r"\w+", "Test_123") # Match object
re.match(r"\w+", "!oops") # None
JavaScript
javascript
const pattern = /\w+/;
console.log(pattern.test("hello123")); // true
console.log(pattern.test("!!!")); // false
๐งผ Want to Match Only Letters?
Use [A-Za-z] instead of \w.
๐ Want to Exclude \w Characters?
Use \W (uppercase W), which matches anything that's not a word character.