How can I match either of two complete words without accepting partial alternatives?
Quick answer
Put the alternatives in a group and place word boundaries around the whole group: \b(?:cat|dog)\b. The | means “or,” and the group makes the boundaries apply to both choices. In Python and JavaScript, this can find either word within a larger string. Word-boundary rules depend on the regex engine, so check them if your text or token definition is more complex. [S1][S2]
The question, the details, the next step.
A practical checklist
Put every alternative inside one group:
(?:FIRST|SECOND).Place a word boundary before and after the complete group:
\b(?:FIRST|SECOND)\b.Test one sentence containing each desired word.
Test longer strings that contain each alternative as a substring.
Check whether your engine’s word-boundary rules fit your text.
A few more useful answers
Will this match a word inside a sentence?
Yes. A search or test using the pattern can find either complete word within a larger string; it does not require the whole string to equal that word.
Why use `(?:...)` instead of ordinary parentheses?
Both group alternatives, but (?:...) is a non-capturing group, so it groups the choices without capturing the group as a value. [S1]
Sources
References used for this guide.
- [S1] Python 3.15 re — Regular expression operations docs.python.org · Checked
- [S2] MDN JavaScript Guide: Character classes and disjunction developer.mozilla.org · Checked
