I’m trying to use the shortest code possible to match non-mango’s digits (17 in this case) in the following test string:
mango:25;orange:17
with the following JavaScript regular expression of negative lookahead:
/(?!mango:)\d+/
I thought that it would match digits which does not have mango: before them. Somehow, it actually matches digits which have mango: before them (25 in this case). Here is a demo on RegExr.
I’m confused.
>Solution :
Use a negative lookbehind instead
and move the column : out of it
/(?<!mango):(\d+)/g
https://regex101.com/r/E8joGx/1
(?<!mango) Not preceded by "mango"
: Preceded by column
(\d+) Match one or more digits
(g Global)
because the unwanted word "mango" lays behind. So in pseudocode: (no "mango" behind):(One or more numbers)
"How to correctly use negative lookahead"
that would be in the case where you want to i.e: match words not followed by a specific match. Take for example:
you want to match all properties where the quantity is not 0
kiwi:0;mango:25;orange:17
that’s where the negative lookahead comes at play, since the "look ahead":
/(\w+):(?!0;)/g
https://regex101.com/r/j28S3y/1
(\w+) Match character a-zA-Z0-9_ one or more time
: Followed by column
(?!0;) Not followed by "0;"
(g Global)