ThibaudBrrd
ThibaudBrrd

Reputation: 23

regex next pattern number = previous pattern number + 1

I am trying create a regex pattern to check a string containing two years spearated by '-' where year B = year A + 1 and these dates are between 2000 and 2099 (date starting by 20)

For now I have a regex expression like this /^20[0-9]{2}-20[0-9]{2}$ it's/g but i don't know how to add a rule like "year B = year A - 1"

I would like to have these results when I do a preg_match :

2009-2010 -> true
2019-2020 -> true
2020-2021 -> true

1999-2000 -> false
2001-2099 -> false
2013-2020 -> false
2099-2100 -> false
2000-2100 -> false

Upvotes: 2

Views: 99

Answers (1)

The fourth bird
The fourth bird

Reputation: 163362

You can not do math using a regex

You could capture the 2 numbers with 2 capture groups. Using php, you can check if the values are between the thresholds of 2000 and 2099 and check if the first value plus one equals the second one.

$strings = [
    "2009-2010",
    "2019-2020",
    "2020-2021",
    "1999-2000",
    "2001-2099",
    "2013-2020",
    "2099-2100",
    "2000-2100"
];

$pattern  = "/^(20\d\d)-(20\d\d)/";
foreach ($strings as $str){
    if (preg_match($pattern, $str, $match)) {
        if (intval($match[1]) + 1 === intval($match[2])) {
            echo "$str is correct". PHP_EOL;
        }
    }
}

Output

2009-2010 is correct
2019-2020 is correct
2020-2021 is correct

Upvotes: 1

Related Questions