regex word boundary \b — match whole words only
Quick Answer
// Match "cat" as a whole word — not "cats", "concatenate"
/\bcat\b/
// JavaScript
'The cat concatenate scat'.match(/\bcat\b/g)
// ['cat']
# Python
import re
re.findall(r'\bcat\b', 'The cat concatenate scat')
# ['cat']
Usage
Without \b, a pattern like /cat/ matches inside "concatenate" and "scat".
Other causes & fixes
What counts as a word boundary
\b matches at a position between a word character (\w: [a-zA-Z0-9_]) and a non-word character.
// Boundaries in "hello world":
// |hello| |world|
// ^ between start-of-string and 'h' → \b
// ^ between 'o' and ' ' → \b
// ^ between ' ' and 'w' → \b
// ^ between 'd' and end-of-string → \b
\B — match NON-word boundary
// Match "cat" only inside a longer word
/\Bcat\B/.test('concatenate') // true
/\Bcat\B/.test('cat') // false
Replace whole words only
// JavaScript
'foo foobar foo'.replace(/\bfoo\b/g, 'baz')
// 'baz foobar baz' — foobar is untouched
# Python
import re
re.sub(r'\bfoo\b', 'baz', 'foo foobar foo')
# 'baz foobar baz'
Related