McRui
McRui

Reputation: 1931

Conditional regex php with limited length

I'm trying to set a regex validation but there's one condition that passes and shouldn't. Seems like I'm missing something. Bellow the regex and what I'm trying to validate. Thanks for any help on this.

My regex:

~^(?=([a-z]{2}))[a-z]{2}[0-9]{6}$|(?=([a-z]{1}))[a-z]{1}[0-9]{6}[a-z]{1}$~i

Data that should validate (two characters plus 6 digits OR on character plus 6 digits plus one character):

AB123456

A123456B

Data that should not validate. My problem is if a character is added after a valid AB123456 it shouldn't pass.

AB123456A

A123456AB

Upvotes: 0

Views: 92

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626932

When you need to match multiple characters with a regex, you should use limiting quantifiers - and you did. However, when you need to **restrict the length to N characters matched, you should use zero width assertions.

Since your problem is matching entire strings, you need the anchors: ^ and $ (end of string). When validating, I'd rather recommend \A instead of ^ and \z (that only matches at the end of the string) instead of $ (that may match before the last newline).

Note you do not need conditional expressions, you need grouping.

  /\A[a-z](?:[a-z]\d{6}|\d{6}[a-z])\z/

Pattern details:

  • \A - start of string anchor
  • [a-z] - a lowercase letter
  • (?:[a-z]\d{6}|\d{6}[a-z]) - either of the two alternatives:
    • [a-z] - a lowercase letter
    • \d{6} - six digits
      or
    • \d{6} - six digits
    • [a-z] - a lowercase letter
  • \z - end of string.

Upvotes: 2

Sverri M. Olsen
Sverri M. Olsen

Reputation: 13283

I think you are complicating this.

You want to match two similar patterns. You can do clever look-behinds/aheads and stuff like that, but what you want in this particular case is much more easily solved by simply matching the patterns separately:

/(?:[a-z]{2}\d{6})|(?:[a-z]\d{6}[a-z])/

Upvotes: 0

Related Questions