Regex匹配年,但不匹配javascript中的其他数字

regex to match year but not other numbers in javascript

本文关键字:javascript 其他 数字 不匹配 Regex      更新时间:2023-09-26

这是我的问题,假设我有几个字符串,字符串中有数字,或者没有,然后在字符串的末尾有年份或年份范围。我需要能够匹配年份,或年份的范围在结束,但不是字符串中的数字。下面是我所说的

的一个例子
var str = 'CO2 emissions per capita 1990-2010'; //when run here I should get 1990-2010
var str2 = 'GHG emissions with LUCF 2010'; // when run from here I should get 2010

我已经非常接近几次了,但我的问题是我要么匹配CO2中的2与年份,要么在其他字符串中可能有一个(),并且也得到匹配。以下是我到目前为止尝试过的正则表达式。

var numRegex = /(['d-_'s])+$/;
var noTextRegex = /([^a-zA-Z's]+)/;
var parts = numRegex.exec(str); //this matches the 2 in CO2
var partsTry2 = noTextRegex.exec(str); //this matches the 2 in CO2 as well but also matches () in other strings.

我从来都不太擅长使用正则表达式,它总是躲着我。任何帮助都将非常感激。谢谢你

你可以这样做:

"ABC 1990-2010".match(/('d{4}-'d{4}|'d{4})/g)
OUTPUT: ["1990-2010"]
"ABC 1990-2010 and also 2099".match(/('d{4}-'d{4}|'d{4})/g)
OUTPUT: ["1990-2010","2099"]
"ABC 1990 and also 2099".match(/('d{4}-'d{4}|'d{4})/g)
OUTPUT: ["1990","2099"]
"ABC 1990".match(/('d{4}-'d{4}|'d{4})/g)
OUTPUT: ["1990"]

"我需要能够匹配年份,或年份范围在末尾但是而不是字符串中的数字。"

这个怎么样?

var yearRegex = /('d{4}|'d{4}'-'d{4})$/g;
"Blabla blabla 1998".match(yearRegex);//>>>["1998"]
"Blabla blabla 1998 aaaa".match(yearRegex);//>>> null
"Blabla blabla 1998-2000".match(yearRegex);//>>>["1998-2000"]

年份总是四位数吗?为什么不直接说出来呢?

/('d'd'd'd)/

或者,更优雅的:

/('d{4})/