-1

I need help with this regular expression check. I'm new to regular expressions so please bail me out. Here's what I'm trying to do:

I'm trying to check if this date ranges both have months in their declaration e.g. Feb 10 - Feb 12 is correct while Feb 10 - 12 should fail. Also, some date instances may not have spaces between either the month and the day or the - and the month or date. Here's my code.

preg_match("/([A-Za-z]{3}\ *?\d{1,2}).*?\g{1}/", "Feb10 -feb 13")

but it keeps failing.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
toonday
  • 501
  • 4
  • 13
  • 1
    Seems like you want [`([A-Za-z]{3}\ *?\d{1,2}).*?(?1)`](https://regex101.com/r/9t9ugb/1). Did you try to use a subroutine rather than a backreference? – Wiktor Stribiżew Mar 15 '18 at 14:04
  • 2
    Try [`([A-Z]{3} *\d{1,2}) *- *(?1)`](https://regex101.com/r/3xCJ3l/1) – ctwheels Mar 15 '18 at 14:04
  • Thanks guys, both solutions work. – toonday Mar 15 '18 at 14:12
  • 1
    I think regex is the wrong tool for your task. What about `XYZ 12 - abc 34` ? Are these good dates?. Find a way to split the range into two strings. Remove any space. Then simply `$d=date_parse_from_format( "Mj","Feb10");` – Paolo Mar 15 '18 at 14:20

1 Answers1

0

As per my original comment below the question.

See regex in use here

([A-Z]{3} *\d{1,2}) *- *(?1)
  • ([A-Z]{3} *\d{1,2}) Capture the following into capture group 1
    • [A-Z]{3} Match any 3 uppercase ASCII letters. Adding the i flag allows us to also match lowercase variants
    • * Match any number of spaces
    • \d{1,2} Match one or two digits
  • * Match any number of spaces
  • - Match this literally
  • * Match any number of spaces
  • (?1) Recurse the first subpattern
ctwheels
  • 21,901
  • 9
  • 42
  • 77