Regex匹配年,但不匹配javascript中的其他数字
regex to match year but not other numbers in javascript
这是我的问题,假设我有几个字符串,字符串中有数字,或者没有,然后在字符串的末尾有年份或年份范围。我需要能够匹配年份,或年份的范围在结束,但不是字符串中的数字。下面是我所说的
的一个例子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})/
相关文章:
- 播放当前视频时如何停止其他视频?JavaScript
- 如何覆盖锚点元素's href目标,并在我点击转到目标javascript时删除其他错误
- 如何将我的javascript库公开给其他客户端使用
- Javascript阻止其他Javascript代码
- 如何在Javascript中验证日期期间与其他日期期间的交叉
- Javascript的某些部分在Chrome中不起作用,但在其他浏览器中可以完美工作
- 网页上失败的javascript会导致所有其他脚本失败
- Facebook Javascript API:'/我/相册'不适用于其他用户
- SVG使用Javascript将形状平滑地变形为其他预定义的形状
- V8或其他C++JavaScript解释器中的Continuations
- JavaScript在其他页面上用html内容填充文本框
- 如何在不保存到其他变量的情况下更改JavaScript中的值
- 在其他javascript框架模板中运行angular指令
- 确定Twig(或JavaScript)中的国际日期格式,以便在其他地方使用
- 用户名输入如果其他块不能正常工作/Javascript-jQuery-AJAX
- 如何隐藏空<span>在IE中使用javascript.(注意,在其他浏览器中工作正常)
- 如何在javascript画布中使一个矩形位于所有其他矩形之上
- 如何使用javascript从同一浏览器下的其他页面获取URL?有可能吗
- 当请求php脚本生成的图像时,如何使用javascript/其他方法以某种格式打印日期
- 网站使用跟踪与Colfusion/JavaScript/其他