简体   繁体   English

正则表达式以数字形式查找年份

[英]regex to find year in string with numbers

I'm trying to find a valid year between 1900 and now in strings like this: 5050.2011.DVD.XviD.AVI.117715.imported 我正在尝试使用以下字符串查找1900年到现在之间的有效年份:5050.2011.DVD.XviD.AVI.117715.imported

I'm looking for 4 digits that aren't surrounded by other digits and start with 19 or 20. 我正在寻找4位数字,这些数字不会被其他数字包围,并且以19或20开头。

So far this is what I have, but the expression returns 2011,20. 到目前为止,这就是我所拥有的,但是表达式返回2011,20。

/(?!=\d)(19|20)[0-9][0-9](?!\d)/

How do I fix this? 我该如何解决?

Use split >> 使用拆分>>

s.split(/[^\d]/).filter(function(n){if((n>=1900)&&(n<=2099))return n})​

Check this demo . 检查这个演示

This regex would return all the years between 1900-2099. 此正则表达式将返回1900年至2099年之间的所有年份。

[^0-9](19|20)[0-9]{2}[^0-9]

Now, run another regex on the above returned results: 现在,对上面返回的结果运行另一个正则表达式:

(19|20)[0-9]{2}

To explain you what's happening, first regex weeds out all the un-needed characters, and returns a string like .2012. 为了说明您的情况,请先使用正则表达式清除所有不需要的字符,然后返回类似.2012.的字符串.2012. .

And the second regex extracts the year from .2012. 第二个正则表达式从.2012.提取年份.2012. and returns 2012 . 并返回2012


But if you want to be specific, every 10 years, you'll have to update the regex yourself: 但是,如果要具体化,每十年,您必须自己更新一次正则表达式:

[^0-9]((19[0-9]{2})|(20[0-1][0-9]))[^0-9]

See the second last [0-1] in the regex? 看到正则表达式中倒数第二个[0-1]吗? This is what you'll have to update every 10 years to the second last digit of the currect year. 这是您必须每10年更新一次到当前年份的倒数第二位。

For example, if it was 2023, you'll update it as: [0-2][0-9] 例如,如果是2023,则将其更新为: [0-2][0-9]

Alternatively, you could use Array.filter here: 另外,您可以在此处使用Array.filter

'5050.2011.DVD1943.XviD.AVI+117715.imported'
 .split(/[^\d]/ /* or /\D/ */)
 .filter(function(a){return +a>1899 && +a<=(new Date).getFullYear();});
 //=> ['2011','1943']

Or use match and filter : 或使用matchfilter

'5050.2011.DVD1943.XviD.AVI+117715.imported'
 .match(/[^\D]+/g /* or /\d+/g */)
 .filter(function(a){return +a>1899 && +a<=(new Date).getFullYear();});
 //=> ['2011','1943']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM