1

Here is my issue, let's say I have a few strings with a number in the string, or not, and then a year, or range of years at the end of the string. I need to be able to match the year, or range of years at the end but not the numbers in the string. Here's an example of what I mean

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

I have gotten really close a couple of times but my problem is I am either match the 2 in CO2 with the years, or in other strings there might be a () in it and that gets matched as well. Here are the regexs I have tried so far.

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.

I have never really been too good with regex, it has always eluded me. Any help would be greatly appreciated. Thank you

Neglected Sanity
  • 1,770
  • 6
  • 23
  • 46
  • `/\d{4}(?:-\d{4})?/g` You can use capturing groups if you need the years to be held individually. It matches a sequence of 4 digits optionally followed by a hyphen and 4 more digits. Put `\s*` on either side of the hyphen if you need optional spaces. – cookie monster May 25 '14 at 17:42
  • @TrentonMaki I saw that one but it would not work for what I needed because it would match things that weren't specifically at the end of the string. The string I am dealing with can have any number of digits in the string at any place in the string, but I only need to care about the end of the string and whether it has a single year or year range. – Neglected Sanity May 26 '14 at 13:59

3 Answers3

2

You can do this:

"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"]
Niels
  • 48,601
  • 4
  • 62
  • 81
1

"I need to be able to match the year, or range of years at the end but not the numbers in the string."

How about this?

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"]
Alcides Queiroz
  • 9,456
  • 3
  • 28
  • 43
  • Perfect thank you much. The other solution by Niels looked good but it would have gotten mis matches because of matching in the middle of the string. This worked perfectly. Thank you, much appreciated – Neglected Sanity May 26 '14 at 13:56
0

Are they always four-digit years? Why not just be explicit about that?

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

Or, more elegantly:

/(\d{4})/
Buck Doyle
  • 6,333
  • 1
  • 22
  • 35