Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to correctly use negative lookahead?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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) 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading