【问题标题】:regex to match year but not other numbers in javascript [duplicate]正则表达式匹配年份但不匹配javascript中的其他数字[重复]
【发布时间】:2014-07-14 12:29:07
【问题描述】:

这是我的问题,假设我有几个字符串,字符串中是否有数字,然后是年份,或者字符串末尾的年份范围。我需要能够匹配最后的年份或年份范围,但不能匹配字符串中的数字。这是我的意思的一个例子

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.

我对正则表达式从来都不是很好,它总是让我望而却步。任何帮助将不胜感激。谢谢

【问题讨论】:

  • /\d{4}(?:-\d{4})?/g 如果您需要单独保存年份,您可以使用捕获组。它匹配一个 4 位数字序列,可选地后跟一个连字符和 4 个数字。如果您需要可选空格,请将\s* 放在连字符的任一侧。
  • @TrentonMaki 我看到了那个,但它不能满足我的需要,因为它会匹配字符串末尾没有特别指定的东西。我正在处理的字符串可以在字符串中的任何位置有任意数量的数字,但我只需要关心字符串的结尾以及它是否具有单个年份或年份范围。

标签: javascript regex


【解决方案1】:

“我需要能够在最后匹配年份或年份范围,但是 而不是字符串中的数字。”

这个怎么样?

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"]

【讨论】:

  • 完美,非常感谢。 Niels 的另一个解决方案看起来不错,但由于在字符串中间匹配,它会得到不匹配。这非常有效。谢谢,非常感谢
【解决方案2】:

你可以这样做:

"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"]

【讨论】:

    【解决方案3】:

    他们总是四位数的年份吗?为什么不直接说清楚呢?

    /(\d\d\d\d)/
    

    或者,更优雅:

    /(\d{4})/
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多