如何提取与某些模式不匹配的数字?

时间:2022-09-13 11:59:12

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).

我需要提取大于3位数且不包含给定范围内的年份的数字(例如,从19xx年到2020年,XX总是在字符串的末尾)。

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.

当我用“something 2012”测试这个表达式时,我总是得到结果012。我需要得到零。

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?

为什么这个表达式与日期的结束不匹配?

2 个解决方案

#1


2  

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.

它丢弃了一些东西,然后尝试匹配2012,但由于您的负面前瞻断言而失败,然后尝试匹配012,它成功了,因为确实,012与您的负面前瞻性断言不匹配。

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.

请看这里的演示:http://rubular.com/r/FLiehrUEp8。

#2


1  

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

1900年- 1900年应该是正则表达式\ b(\ d +)\ b(? < !(?:19 \ d { 2 } | 20[0]\ d))

#1


2  

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.

它丢弃了一些东西,然后尝试匹配2012,但由于您的负面前瞻断言而失败,然后尝试匹配012,它成功了,因为确实,012与您的负面前瞻性断言不匹配。

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.

请看这里的演示:http://rubular.com/r/FLiehrUEp8。

#2


1  

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

1900年- 1900年应该是正则表达式\ b(\ d +)\ b(? < !(?:19 \ d { 2 } | 20[0]\ d))