Tharindu Dasun
Tharindu Dasun

Reputation: 13

I want regex to match a pattern that can only have either two alphabet characters or numeric characters

I want a regex for PHP that can match two alphabetic characters or two numeric characters. For example:

AB or 45

The characters can't be mixed with alphabetic and numeric.

^(\w)\1|[A-Z|0-9]{2}$

I used the above regex but it doesn't work correctly.

Upvotes: 1

Views: 128

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You may use

preg_match('~^(?:[A-Za-z]{2}|\d{2})$~', $s, $match)

The ^(?:[A-Za-z]{2}|\d{2})$ pattern matches two ASCII letters or two ASCII digits.

See the regex demo and the regex graph:

enter image description here

Details

  • ^ - start of string
  • (?:[A-Za-z]{2}|\d{2}) - a non-capturing group matching either
    • [A-Za-z]{2} - two ASCII letters
    • | - or
    • \d{2} - two digits
  • $ - end of string.

To make it match all Unicode letters, you may use

preg_match('~^(?:\p{L}{2}|[0-9]{2})$~u', $s, $match)

Upvotes: 1

Related Questions