Halle
Halle

Reputation: 3584

Excluding a single pattern from a perl search and replace with word boundary matching

After asking this perl newbie question, I have a perl newbie follow-up. I have discovered the one case in which using the word boundary fails for the purposes of my application which does this regex search and replace over a set of files:

s/\bcat\b/cat_tastic/g

Which is that I would also like for -cat to not be a match for replacement, although it is currently a match since the hyphen is considered a word boundary. I have read up on word boundaries but what I've learned is that creating a change to boundary conditions when using \b is non-trivial. How do I exclude "-cat" from being searched and replaced? So the end result is:

:cat { --> :cat_tastic {
:catalog { --> no change
-cat { --> no change

This doesn't have to be part of the one line search and replace, it can also be a condition previous to the search and replace which controls whether the search and replace is executed, although having it in the search and replace would be most useful.

Upvotes: 2

Views: 1898

Answers (2)

alexis
alexis

Reputation: 50220

This is not a newbie regexp, but it seems like the best fit for your pattern: Use a "negative lookbehind" expression, to say "I want what I match NOT to follow a hyphen:

s/(?<!-)\bcat\b/cat_tastic/g

Addendum: This does the job, but a more general approach (also portable to languages with less fancy regexps) is to split this kind of problem into two: cat after NOT a hyphen, or cat at the start of a string:

s/([^-])\bcat\b|^\bcat\b/\1cat_tastic/g

Or better yet:

s/([^-]|^)\bcat\b/\1cat_tastic/g

Upvotes: 3

TLP
TLP

Reputation: 67900

If the "word boundary" in your case only occurs with "a-z, A-Z, 0123456789, and the underscore and hyphen" as per your comment, you can use a character class:

s/(?<![\w-])cat(?![\w-])/cat_tastic/g

Word boundary \b occurs where characters matching \w does not border to another \w character. To add hyphen to that, the simplest way is to use a character class like above.

Upvotes: 0

Related Questions