Master Python’s \w and \W: When to Use Each Regex Token
This article explains the meanings and differences of Python regex tokens \w and \W, demonstrates how they match various characters through step‑by‑step examples, and shows why \w fails with symbols like hyphens while \W succeeds, helping readers master practical regex usage.
Continuing the series on Python regular expressions, this tutorial focuses on the special characters \w and \W. \w matches any word character: uppercase letters A‑Z, lowercase letters a‑z, digits 0‑9, and the underscore "_" (i.e., the set [A-Za-z0-9_]). The dot . matches any character, which is a broader set.
Below are visual demonstrations of how these tokens behave with different input strings.
Using a character class [A-Za-z0-9_] (equivalent to \w ) successfully matches the target string.
Replacing the explicit class with \w still matches successfully.
Changing the input string to "加A油" continues to match.
Using "加_油" also matches because the underscore is included in \w .
When the string contains a hyphen "加-油", \w fails because "-" is not part of the word‑character set.
The opposite token \W matches any character not in [A-Za-z0-9_] . Replacing \w with \W now matches the hyphen case.
Changing the string to "加 油" (with a space) shows that \w cannot match, while \W succeeds.
Finally, replacing the hyphen with an underscore "加_油" results in no match for either token, demonstrating that the underscore is considered a word character.
By the end of these examples, you should understand when to use \w versus \W in Python regular expressions.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
