Programming & Development / April 18, 2025

Understanding \w in Regular Expressions

regex regular expression \w word character shorthand character class alphanumeric underscore

๐Ÿง  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.


Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex