Home > Enterprise >  In a given string, match all numbers where a certain word is not present either ahead or behind it [
In a given string, match all numbers where a certain word is not present either ahead or behind it [

Time:11-22

I have a string like

"10.0 banana 30 apple 50 TOM 70 mango 100 peach 33 TOM 4.5"

and from this, I want to match only numbers which do not have the word TOM either behind or ahead of them.

So match should be only numbers 10.0, 30, 100; numbers 50, 70, 33 and 4.5 should not be matched.

Regex101. I have tried with negative lookbehinds and negative lookaheads, but I am missing something, it is not working as expected.

CodePudding user response:

You can use negative lookaround patterns like this:

(?<!\bTOM )(?<![\d.])\d (?:\.\d )?(?![\d.])(?! TOM\b)

Demo: https://regex101.com/r/v8IaEu/1

  • Related