Home > other >  Regex replace all occurences of a word unless its the last word
Regex replace all occurences of a word unless its the last word

Time:07-22

I am trying to replace all occurrences of a word unless the word is at the end of the sentence, for example:

The quick brown fox jumps over the lazy dog

If I am removing the word dog, the above sentence should remain the same,

The quick brown fox jumps over the lazy dog

but if the sentence was:

The dog was lazy

dog would be removed from the sentence and would have the following result;

The was lazy

I am not well versed with regex I tried something like this;

(dog)(?=(dog))

Apparently this is wrong, because it does not remove any.

CodePudding user response:

You can use

/\bdog\b(?!$)/g

If you need to account end of any line:

/\bdog\b(?!$)/gm

Details:

  • \b - a word boundary
  • dog - a word dog
  • \b - a word boundary
  • (?!$) - a negative lookahead that fails the match if there is end of string immediately to the right of the current location.

See the regex demo.

Note: to also remove initial whitespace, add \s*: \s*\bdog\b(?!$).

  • Related