In Perl, you can use the 'word boundary' zero-length pattern \b. So you can do s/\bMUST\s*NOT\b/{\\MUSTNOT}/g and s/\bMUST\b/{\\MUST}/g Alternately, you could do s/\bMUST(?: (NOT))?\b/{\\MUST$1}/g to match and replace them both in one pass.