tags:

views:

42

answers:

2

I am using the following regex to match an account number. When we originally put this regex together, the rule was that an account number would only ever begin with a single letter. That has since changed and I have an account number that has 3 letters at the beginning of the string.

I'd like to have a regex that will match a minimum of 1 letter and a maximum of 3 letters at the beginning of the string. The last issue is the length of the string. It can be as long as 9 characters and a minimum of 3.

Here is what I am currently using.

'/^([A-Za-z]{1})([0-9]{7})$/'

Is there a way to match all of this?

+3  A: 

You want:

^[A-Za-z]([A-Za-z]{2}|[A-Za-z][0-9]|[0-9]{2})[0-9]{0,6}$

The initial [A-Za-z] ensures that it starts with a letter, the second bit ([A-Za-z]{2}|[A-Za-z][0-9]|[0-9]{2}) ensures that it's at least three characters long and consists of between one and three letters at the start, and the final bit [0-9]{0,6} allows you to go up to 9 characters in total.

Further explaining:

^                    Start of string/line anchor.
[A-Za-z]             First character must be alpha.
( [A-Za-z]{2}        Second/third character are either alpha/alpha,
 |[A-Za-z][0-9]       alpha/digit,
 |[0-9]{2}            or digit/digit
)                      (also guarantees minimum length of three).
[0-9]{0,6}           Then up to six digits (to give length of 3 thru 9).
$                    End of string/line marker.
paxdiablo
Won't this match things like: "A0A"?
Sheldon L. Cooper
Sheldon, the original did, you caught me mid-edit. This current one fixes that problem by ensuring that characters 2 and 3 are of the forms `AA`, `A0`, or `00`.
paxdiablo
Looks good to me now. +1
Sheldon L. Cooper
It is good. Thanks so much, guys.
tom
BTW: Who would have thought that it was a good idea to have to wait 10 minutes to accept an answer?
tom
@tom, I gather it's to stop questioners accepting the first answer which seems right. There may well be others coming that are better. This is a well documented fastest-gun problem found in the early SO days. Questioners will probably either accept fast (as soon as they get something workable, which may not be the best answer) or accept slow (a couple of days to ensure a lot of possible different answers have shown up).
paxdiablo
@Pax, Thanks for the explanation. I'm new to SO and not very familiar with how it works in detail so I appreciate knowing where and why the logic surrounding that 10 minute acceptance box came from. Hey, thank again for all the help, Pax.
tom
@ Pax, I just came back and noticed your edit explaining the code. Thanks, that is very helpful, indeed.
tom
A: 

Try this:

'/^([A-Za-z]{1,3})([0-9]{0,6})$/'

That will give you from 1 to 3 letters and from 3 to 9 total characters.

JoshD
This will match "A", which is too short.
Sheldon L. Cooper