简体   繁体   中英

Regex replace all occurences of a word unless its the last word

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.

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(?!$) .

To remove a word and one or more non-word characters if there is another word ahead:

\bdog\W+\b
  • \b matches a word boundary ...more about \b and \w
  • Upper \W is the negation of \w which is a short for word character

See this demo at regex101 (I used [^\w\n] instead \W for not skipping lines in multiline-demo)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM