Why does a regex character class match more than the characters I expected?
Quick answer
A character class matches one character from its set. A hyphen between two characters can define a range, so [A-z] is a range, not just the endpoints. To include a literal hyphen, put it first or last in the class, or escape it. In Python re and JavaScript’s non-v mode, [a-z-] allows lowercase letters or a hyphen. JavaScript v mode has additional escaping rules. [S1][S2]
The question, the details, the next step.
A practical checklist
Write down the exact characters that should be accepted before choosing a range.
Check whether each hyphen is intended as a range marker or a literal character.
Put a literal hyphen first or last in the class, or escape it for the regex mode you use.
Name the JavaScript regex mode; do not apply non-
vplacement guidance tovmode.Test accepted and rejected examples, including punctuation near range endpoints.
A few more useful answers
Does `[a-z]` match the whole word?
No. A character class matches one character from its set. A quantifier such as + can allow a run of those characters.
Is `[a-z-]` a way to include a hyphen?
Does `^` negate a character class wherever it appears?
In Python, ^ negates the class only when it is first; elsewhere it is literal. The cited JavaScript information does not establish this detail, so check the rules for your JavaScript regex mode. [S1]
Sources
References used for this guide.
- [S1] Python 3.15.2: Regular expression operations docs.python.org · Checked
- [S2] MDN: JavaScript character classes developer.mozilla.org · Checked
