Home > Net >  RegEx: If second group in place, ignore condition
RegEx: If second group in place, ignore condition

Time:09-28

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);

CodePudding user response:

The reason your pattern matches too much is because this part {6,} matches 6 or more digits which will match all 6 or more consecutive digits in the first place.

Then this part matches an optional hyphen -? and the last group (([0-9]{5})?) repeats 1 or more times. But the group matches 5 optional digits.

Because all the quantifiers except for the first one are optional, it can match most of the example strings.


You could match either 6 digits, a hyphen followed by 1 digits, or the other variants with a set number in the quantifier {n}

^(?:\d{6}-\d |\d{8}|\d{11}|\d{13})$
  • ^ Start of string
  • (?: Non capture group
    • \d{6}-\d match 6 digits, - and 1 digits
    • | Or
    • \d{8}|\d{11}|\d{13} Match 8 or 11 or 13 digits
  • ) Close non capture group
  • $ End of string

Regex demo | PHP demo

If the number of digits after the hyphen should be 5:

^(?:\d{6}-\d{5}|\d{8}|\d{11}|\d{13})$

CodePudding user response:

One straightforward regex for this based on the given restrictions:

^\d{6}(-\d |\d{2}|\d{7}|\d{5})$

(\d{6}) first 6 digits

below are grouped by OR |

  • -(\d ) 2nd group
  • (\d{2}) 6 2 = 8 digits
  • (\d{7}) 6 7 = 13 digits
  • (\d{5}) 6 5 = 11 digits

Regex Sample

  • Related