How to Match Whole Words Using Regex?
Using word boundary anchors in regex allows you to match complete words, ensuring no partial matches occur. This is essential for accurate text processing.
Formula Genius can generate a draft from a plain-English prompt. Supported formulas can be checked with sample cases; review the coverage on the result.
The formula
"Match whole words only (not partial matches) using word boundary anchors"
\bword\b
This regex pattern matches the exact word 'word' only when it appears as a whole word.
Step-by-step breakdown
- The '\b' at the beginning indicates a word boundary before the word.
- The 'word' is the specific term you want to match.
- The '\b' at the end indicates a word boundary after the word.
- This ensures that 'word' is not part of another word (e.g., 'wording').
Edge cases & warnings
- Matching 'word' in 'wording' will fail due to the lack of boundaries.
- Searching for 'word' in a sentence with punctuation will succeed if correctly placed.
- Case sensitivity may affect matches unless specified with flags.
- Trailing spaces or line breaks can affect boundary detection.
Examples
"This is a word in a sentence."
Match found: 'word'
"The wording is different."
No match found
Frequently asked questions
What does \b mean in regex?
\b denotes a word boundary in regex.
Can I match multiple words?
Yes, you can use the pattern \b(word1|word2)\b to match either word.
Is regex case-sensitive?
By default, regex is case-sensitive unless specified otherwise.
Can't find what you need?
Describe a formula in plain English. Formula Genius drafts and explains it, and can check supported formulas on sample cases.