How do Unicode letters and digits affect regex matching in Python and JavaScript?
Quick answer
Do not assume that \w, \d, or case-insensitive matching mean the same thing in Python and JavaScript. In Python re, Unicode string patterns use Unicode-aware rules for \w and \d by default, while re.ASCII narrows those shorthand classes. JavaScript documents \w as basic-Latin letters, digits, and underscore, and \d as [0-9]. Choose a specific property or range for your intended text, then test with your actual flags.
The question, the details, the next step.
A practical checklist
Write down whether the field allows ASCII only or Unicode letters and digits.
Specify whether underscore, punctuation, and whitespace are allowed.
Check the language, regex engine, pattern type, and active flags.
Test intended and rejected characters individually, including non-ASCII cases relevant to your requirement.
Run the test set in each implementation; do not assume Python and JavaScript behave identically.
A few more useful answers
Does Python `\w` mean every Unicode character that is a letter?
No. Python documents \w for Unicode string patterns as Unicode alphanumeric characters plus underscore; that is not a claim that it matches every character someone might describe as a letter. Define and test the exact property your application needs. [S1]
Does JavaScript `\d` match Unicode decimal digits?
MDN documents JavaScript \d as equivalent to [0-9]. If you need a broader digit rule, choose an explicitly suitable Unicode property or other documented pattern and test it in the intended mode. [S2]
Will the same regex behave identically in Python and JavaScript?
Not necessarily: their documented shorthand-class definitions differ, and flags or modes can affect behavior. Verify each implementation against the same expected test cases.
Sources
References used for this guide.
- [S1] Python 3.15.2 re — Regular expression operations docs.python.org · Checked
- [S2] Character classes — JavaScript | MDN developer.mozilla.org · Checked
