RRegexBuilder
Get RegexBuilder

RegexBuilder · regex answers

Regex word boundary explained

/\bcat\b/gi

\b is a zero-width position between a word character and a non-word character. It matches cat in 'the cat sat' but not inside 'concatenate', which is the usual reason a naive search-and-replace corrupts a file.

What each part does

\ba boundary — matches a position, consumes nothing
catthe literal word
\bthe boundary on the other side

Tested against real input

Every row below was run through the engine when this page was built. The third column is the substring the pattern actually matched.

InputResultMatched
the cat satmatchescat
CATmatchesCAT
a cat.matchescat
concatenateno match
categoryno match
bobcat5no match

The mistake to avoid

Using \b next to punctuation and expecting it to hold. In 'cat-like' there is a boundary after cat, so \bcat\b matches — because the hyphen is a non-word character.

Try it on your own text

Paste this pattern and your input, see each match highlighted with its capture groups, step through what the engine did, and get the equivalent syntax for JavaScript, Python, Java, Go and PCRE.

Open RegexBuilder

Other regex answers