0

I have a list of years like this:

2018-

2001–2020

1999-

2005-

I would like to create a regex to match the year with these criteria:

xxxx-     matches xxxx

yyyy-nnnn matches nnnn

Can you please help me?

I've tried [[:digit:]]{4}$, or alternatively [[:digit:]]{4}-$, but they only partially work.

2
  • Hi, thank you for your comment. This is what I expect: 2018 2020 1999 2005
    – Stefano
    Jul 3, 2020 at 23:32
  • 1
    Are you using R or perl?
    – Shawn
    Jul 4, 2020 at 1:09

3 Answers 3

3

To get the last year in the "range," established by - character, the cleanest way

my $year = (split /-/, $range)[-1];

If there isn't anything after the last delimiter then the last returned element by split is what is before it, so the last element in its return list (obtained with index -1) is either the second given year -- as in 2001-2020 -- or the only one, as in other examples. This performs no checking of input.

With a regex, one way is to seek the last number in the string

my ($year) = $range =~ /([0-9]+)[^0-9]*$/;

where if you use [0-9]{4} then there is a small additional measure of checking.

The POSIX character class [[:digit:]] and its negation [[:^digit:]] (or \P{PosixDigit}) can be used instead if desired, but note that these match all manner of Unicode "digit characters," just like \d and \D do (a few hundred), on top of the ascii [0-9] (unless /a modifier is used).

A full test program, for both

use warnings;
use strict;
use feature 'say';

my @ranges = qw(2018- 2001-2020 1999- 2005-);

foreach my $range (@ranges) { 
    my $year = (split /-/, $range)[-1];
    
    # Or, using regex
    # my ($year) = $range =~ /([0-9]+)[^0-9]*$/;
    
    say $year;
}

Prints as desired.

0

We can capture the 4 digits as group, followed by a - at the end ($) of the string and replace with the backreference (\\1) of the captured group

sub(".*(\\d{4})-?$", "\\1", str1)
#[1] "2018" "2020" "1999" "2005"

data

str1 <- c("2018-", "2001-2020", "1999-", "2005-")
0

You can split the text on "-" and get the last number.

x <- c("2018-", "2001-2020", "1999-", "2005-")
sapply(strsplit(str1, '-', fixed = TRUE), tail, 1)
#[1] "2018" "2020" "1999" "2005"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.