regexword-boundary

Regex match entire words only


I have a regex expression that I'm using to find all the words in a given block of content, case insensitive, that are contained in a glossary stored in a database. Here's my pattern:

/($word)/i

The problem is, if I use /(Foo)/i then words like Food get matched. There needs to be whitespace or a word boundary on both sides of the word.

How can I modify my expression to match only the word Foo when it is a word at the beginning, middle, or end of a sentence?


Solution

  • Use word boundaries:

    /\b($word)\b/i
    

    Or if you're searching for "S.P.E.C.T.R.E." like in Sinan Ünür's example:

    /(?:\W|^)(\Q$word\E)(?:\W|$)/i