php – RegEx: If second group in place, ignore condition
As always, I could not trick my brain into fully understanding regular expressions. And now, I am trying to create the regEx with conditions, like if second group matches then change the character quantity
.
This is a set of values that SHOULD match the regEx:
123456-12345
12345678901
12345678
1312345678912
But if there is the second group (after the “-“), the number or characters in first group must be exactly 6 and if there is no second group, the minimum number of chars in 1st group must be == 8 OR == 11 OR = 13, so these SHOULD NOT match:
12345-12345 // 5 + 5 chars
1234567-12345 // 7 + 5 chars
123456 // 6 chars
12345678901234 // >13 chars
1234567890 // 10 chars
123456789088 // 12 chars
This is what I came up with so far:
([0-9]{6,})(-?)(([0-9]{5})?)+
This will match most of the required, but will accept also forbidden versions, like:
123456789-12345
1111111111111111111
The main question is how to differentiate groups conditionally and limit the max char number based if the group exists?
Kind regards,
P.S. And yes, this is meant to be used in PHP request validation (server-side);
Read more here: Source link