Can someone help me with the if in regex I am using a regex compiler I have done this
^\d{2}(02)?(?(1)(0\d$|1\d$|2[0-8]$)|(0[1-9]|1[0-2])(0\d$|1\d$|2\d$|3[0-1]$))
It is to validate correct YYMMDD dates since February only has 28 days but the if gives me an error, not syntax but logical, example:
If I put 200230 this makes it correct for me (although it should not be correct since February does not have 30 days) because it enters the if condition since it did have a 02 after the 2 digits at the beginning:
//entra aqui si el mes es 02 y valida que el día sea menor que 29
(02)?(?(1)(0\d$|1\d$|2[0-8]$)|
since the day is 30 for some unknown reason, it comes out of this:
(?(1)(0\d|1\d|2[0-8])
and enter the second:
(0[1-9]|1[0-2])(0\d$|1\d$|2\d$|3[0-1]$)
and it matches, does anyone know why the if doesn't work for me?
All your logic is perfect until you get to say " for some reason I don't know ".
I tell you that reason following the step by step that the regex engine does:
(02)?
What happens here, as with any regex construct when it fails?
It backtracks . That is, go back to keep trying other combinations that could give a match.
What are you trying?
(02)?
repeated 0 times (by the?
). That is, do not coincide with that group 1.(0[1-9]|1[0-2])
it allows it to match"02"
, and it matches everything.There are many ways to correct it, some are as an example:
Did you read about possessive quantifiers ? It is a
+
continuation of a quantifier. They make it so if you matched a number of reps and later fail, don't try fewer reps. That is, if it matched(02)?+
, you can't try 0 replays when backtracking. That+
extra fixes the problem.Did you see that an IF can ask for a captured group or else use a lookahead? Okay...
Do you want to do the same without an IF? It is only a matter of putting together the 2 alternatives, that they are mutually exclusive (one with February and the other that does not allow February in any way).
(0[13-9]|1[0-2])
matches all months except 02.February has 29 days in leap years . Do you want to blow your head off? Read this question: Validate a dd/mm/yyyy date with regular expressions and see if you can adapt it to yymmdd.