mvbl fst
mvbl fst

Reputation: 5263

How do you extract numbers which do not match some pattern?

I need to extract numbers that are longer than 3 digits and do not include years within a given range (e.g. between 19xx and 2020, where XX is always in the end of the string).

I am currently using the following pattern:

/(?!19[0-9]{2}|200[0-9]|201[0-9]|202[0-9])\d{3,}$/i

When I test the expression with "something 2012", I always get the result 012. I need to get null.

var s = "moose high performance drive belt 2012";
s.match(/(?!19[0-9]{2}|200[0-9]|201[0-9]|202[0-9])\d{3,}$/i);

Why does this expression incorrectly match the end of a date?

Upvotes: 2

Views: 82

Answers (2)

Ωmega
Ωmega

Reputation: 43673

For years 1900 - 2029 it should be regex \b(\d+)\b(?<!(?:19\d{2}|20[0-2]\d))

Upvotes: 1

Andrew Cheong
Andrew Cheong

Reputation: 30273

It discards something , then attempts to match 2012 but fails due to your negative look-ahead assertion, then attempts to match 012, which succeeds because indeed, 012 does not match your negative lookahead assertion.

UPDATE:

This isn't pretty but it's one solution. Perhaps you can simplify it.

    (?!(?:19[0-9]{2}|200[0-9]|201[0-9]|202[0-9])\D)(?<!\d)\d{3,}

See a demo here: http://rubular.com/r/FLiehrUEp8.

Upvotes: 2

Related Questions