0
(0[1-9]|1[0-2])[/]([0-2][0-9]|[3][0-1])

This is for a date format in mm/dd so i want to be able to prevent 02/30, 02/31 ...

can I do an if else statement with this regex to accomplish that?

psj01
  • 3,075
  • 6
  • 32
  • 63
  • 4
    Why on earth would you want to do this with regex? What about leap years? – jonrsharpe Jan 29 '18 at 17:31
  • You need to split it up into separate patterns for each month length, then combine them all with `|`. – Barmar Jan 29 '18 at 17:32
  • On leap years `(?:[0-9](?:[0-9](?:0[48]|[13579][26]|[2468][048]))|(?:(?:[02468][048]|[13579][26])00))` February goes to 29 days. Without knowing the year though, you're hosed. –  Jan 29 '18 at 17:34
  • Take a look at [my answer on this question](https://stackoverflow.com/questions/46409193/regular-expression-for-date-and-timedd-mm-yyyy-hhmmss-in-qml/46414732#46414732) before you decide to do dates with regex. In it, I explain each part of date matching. You'll see why @jonrsharpe is challenging your decision to use regex for date validation. – ctwheels Jan 29 '18 at 17:34
  • actually i am only doing this for learning purpose.. just want to know how to do an if else inside a reg exp.. :) – psj01 Jan 29 '18 at 17:37
  • @psj01 it depends on your regex flavour. In some regex engines you can use `(?(?=x)yes|no)` where `(?=x)` is the test. – ctwheels Jan 29 '18 at 17:39
  • when you say (?=x) is the test.. is the test variable what ever text that matched so far?... – psj01 Jan 29 '18 at 17:40
  • Date regex for 1900-2999 `^(?:(?:(?:0?[13578]|1[02])([/.-])(?:0?[1-9]|[12]\d|3[01])\1|0?2([/.-])(?:0?[1-9]|1\d|2[0-8])\2|(?:0?[469]|11)([/.-])(?:0?[1-9]|[12]\d|30)\3|(?:0?[1-9]|[1-2]\d|3[0-1])([/.-])(?:0?[13578]|1[02])\4|(?:0?[1-9]|1\d|2[0-8])([/.-])0?2\5|(?:0?[1-9]|[12]\d|30)([/.-])(?:0?[469]|11)\6)(?:(?:19)?\d{2}|2\d{3})|(?:0?2([/.-])29\7|29([/.-])0?2\8)(?:19(?:0[48]|[13579][26]|[2468][048])|2(?:[0-9](?:0[48]|[13579][26]|[2468][048]))|(?:(?:2[048])00)))$` The alternations are the else/if in regular expressions. Parse with http://regexformat.com –  Jan 29 '18 at 17:42
  • @sln dear god... Idk what's worse, my QML regex or that – ctwheels Jan 29 '18 at 17:44
  • Parse it and find out. Mines better _!!_ –  Jan 29 '18 at 17:46
  • Regex conditionals are not used the way conditionals are used in code. I mean, it's _never_ used like that. Regex conditionals are used as a flag test, and nothing else. –  Jan 29 '18 at 17:48

0 Answers0