What regular expression can be used to solve this problem?

Task: A message may contain a date in the format dd.mm.yyyy. In the specified format, dd is an integer from 1 to 31, mm is an integer from 1 to 12, and yyyy is an integer from 1900 to 2012 (if some part of the format is broken, then this substring is dates are not considered). Find all dates that relate to the current year.

  • one
    dd is an integer from 1 to 31. Namely from 1? or from 01? or both are possible? dates that refer to the current year. Is the current year number also offered to receive regular? - Akina
  • both dd options are possible. The current year number must also be obtained using a regular expression. - Gadget
  • Well, to the heap - the legitimacy of the date should be controlled? type on April 31 or February 29 in the year ...
  • Yes, by the way ... no date in the specified range of years can relate to the current year ... - Akina
  • It is unlikely that using regular expressions can make a reliable and easily supported program. Write such parts in a normal programming language. - avp

2 answers 2

JUST FOR FUN

Regular expression that takes into account leap years, the number of days in a month:

https://regex101.com/r/kegjEO/1

(?<![0-9.]) (?P<day> 0?[1-9] | # 1-9 , 01-09 [12][0-9] | # 10-29 3[01] # 30-31 ) \. (?(?=0?[469]|11)(?<!31\.)|) # month of 30 day (?(?=0?2)(?<!3[01]\.)|) # feb not 30 31 (?(?=0?2\.\d\d(?!00)(?:[02468][048]|[13579][26]))|(?<!29\.)) # февраль високосные года и 2000 2400 2800... (?P<month>0?[1-9]|1[12]) \. (?P<year>19[0-9][0-9]|20[0-9][0-9])(?!\d) 

It will work absolutely correctly (if you find errors, write), but I would not recommend using such a regular expression if you do not understand regular expressions.
Everything is trite: you can not fix it if something breaks. Again you have to create a forum thread :)

    I would rewrite the previous speaker a bit:

    https://regex101.com/r/Lui4NG/1

     (?<day>0?[1-9]|[12][0-9]|3[01])(?>.{1})(?(?=0?[469]|11)(?<!31(?>.{1}))|)(?(?=0?2)(?<!3[01](?>.{1})))(?(?=0?2(?>.{1})\d\d(?!00)(?:[02468][048]|[13579][26]))|(?<!29(?>.{1})))(?<month>0?[1-9]|1[12])(?>.{1})(?<year>19[0-9][0-9]|20[0-9][0-9]|[0-9]{2,4})(?!\d) 
    • the “previous” is very relative here, the links to the participants (not speakers) look like this - @ReinRaus - 0xdb