Honza
Honza

Reputation: 23

Two condition in one regular expression

I'm trying to create a regular expression in php with these condition:

 1. Two letters, then six numbers (ha123456).

 2. Or one letter, then seven numbers (j0123456).

Now I have this, but it doesn`t work properly.

[a-zA-Z]{1,2}[0-9]{6,7} 

Any suggestion ? or do i have to check it with function ?

Thanks for reply.

Upvotes: 2

Views: 470

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521914

I would phrase this as:

^[A-Za-z][A-Za-z0-9][0-9]{6}$

This meets both expected inputs, because they both start with a single letter, and end in 6 digits. The only difference is the second character, which can be either a letter or a digit.

Upvotes: 3

hppycoder
hppycoder

Reputation: 1026

There's other ways of doing this but I always like the straight forward regex style of:

([a-zA-Z]{2}[0-9]{6})|([a-zA-Z][0-9]{7})

Demo

It has 2 letters + 6 numbers OR 1 letter and 7 numbers.

Upvotes: 1

Related Questions