Gerard Corboz
Gerard Corboz

Reputation: 13

Regular Expression to match account number consisting of specific 3 character string followed by 9 digits

I'm trying to craft a regular expression which will match an account number which consists of specific 3 characters strings followed by 9 digits. e.g.

abc123456789
xyz123456789
def987654321

I've figured out how to accomplish with the following expression but wanted to know if there was a better way:

abc[0-9]{9}|xyz[0-9]{9}|def[0-9]{9}

Upvotes: 1

Views: 77

Answers (2)

Juan T
Juan T

Reputation: 1219

If the account number can only consist of abc, def or xyz, you can use | specifically for those strings, as pointed out by Jorge Campos:

(abc|def|xyz)\d{9}

However, assuming it can start with any combination of non-numerical characters, this is the most compact way to put it:

\D{3}\d{9}

Upvotes: 1

Jorge Campos
Jorge Campos

Reputation: 23371

You can make the OR only for the specific strings since it is the only one thing changing:

(abc|xyz|def)[0-9]{9}

Upvotes: 5

Related Questions