0

I'm trying to create regex for yyyy+, meaning have a positive match for every year that is greater then year yyyy. for ex. the text is 2017+ and it will have to match for 2017, 2018, 2019 ..., but it will not match 2016. I did a research on the subject, but almost of the results are for yyyy format. To give the context, the data is stored in mongodb database as string in format as yyyy+, yyyy- or yyyy and I will query the documents using regex.

Also, another question is this possible in regex ?

Xoke
  • 984
  • 2
  • 11
  • 17
  • 2
    Possible duplicate of [RegEx: How can I match all numbers greater than 49?](https://stackoverflow.com/questions/8592488/regex-how-can-i-match-all-numbers-greater-than-49) – Lior Kogan Nov 14 '18 at 15:07
  • 1
    Also https://stackoverflow.com/questions/29977086/regex-how-can-i-match-all-numbers-greater-than-954/29977124 – Lior Kogan Nov 14 '18 at 15:08
  • 4
    You probably could do this with regexes, but that's not really what they're for. Just capture the year and then use whichever programming language you're using to compare it to your target year. – jsheeran Nov 14 '18 at 15:09
  • ^^ This. Why not just capture the number (`\d+`), then check whether it's `>`, or `>=`, or `==`, or `<=`, or `<`, the value you wish to compare it to. Trying to perform the whole comparison in one regex is a gross over-complication of the problem. Possible, but almost certainly not the best approach. – Tom Lord Nov 14 '18 at 15:37

1 Answers1

2

Although this kind of task should not be preferred to be done purely by regex and instead should be done in a programming language of your choice using arithmetic comparisons. But just for the sake of academic purposes, you may write a regex something like this, and although there are couple of other ways of doing it, I am doing it with negative look ahead. You may try to do this using alternation forming various cases of numbers that are equal to or greater than 2017 or less than 2017. I've written this regex specifically for 2017+ as mentioned in your post. This regex matches four digit numbers (yyyy as mentioned in your post) that is equal to or greater than 2017.

^(?![10]\d{3})(?!2(?=01[0-6]))(?!2(?=00\d))\d{4}$

Explanation:

  • ^ --> Start of string
  • (?![10]\d{3}) --> Negative look ahead ensuring number is not of this form that starts with zero or one followed by three digits
  • (?!2(?=01[0-6])) --> Negative look ahead ensuring if number starts with 2 then it should not be followed by 010 to 016
  • (?!2(?=00\d)) --> Negative look ahead ensuring if number starts with 2 then it should not be followed by 000 to 009
  • \d{4} --> Matches exactly four digits ensuring it matches yyyy date pattern
  • $ --> End of string

Demo Here

Let me know if this is what you wanted. Else provide some more samples of input output so I can help you better with a more appropriate answer.

Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36