I need a regex string for validating an account code. The code is four characters that has to start with an alpha followed by an alphanumeric then followed by numerals only (i.e. AC23
, D345
, CT75
)
I currently have the following stateme开发者_如何学Cnt that will throw error
if (!Regex.Match(iLineItem.Code, @"^[A-Za-z0-9][A-Za-z0-9]*$").Success)
yield return new RuleViolation("Code has invalid format.", "Code");
How can I change the string to not allow A99A
as a code?
Thanks in advance!
^[a-zA-Z][a-zA-Z0-9][0-9]{2}$
which is made up of...
^
start of string[a-zA-Z]
alpha character only[a-zA-Z0-9]
alphanumeric[0-9]{2}
two digits only ([0-9]
for digit,{2}
for "exactly 2 times")$
end of string
I think you need
"^[A-Za-z][A-Za-z0-9][0-9]{2}$"
Based on your description:
The code is four characters that has to start with an alpha followed by an alphanumeric then followed by numerics only...
^[A-Za-z]
gives you the start of the string with one alpha.
[A-Za-z0-9]
gives you one alphanumeric.
[0-9]{2}$
gives you two numerics at the end of the string.
The expression you want is
^[a-z][a-z0-9][0-9][0-9]$
Make sure you're using the "case insensitive" flag.
My vote for most concise:
i^[a-z][a-z0-9]\d{2}$
The i
at the beginning means "case-insensitive", so you don't have to have a bunch of A-Za-z
s. Some dialects do the flags differently, so make sure you're doing it right.
\d
means "a single digit". It's the same as [0-9]
. However, some dialects don't recognize it, so if yours doesn't, use [0-9]
instead.
Finally, some (very limited) dialects don't accept {2}
(which means "exactly two times"). If yours doesn't, you'll need \d\d
.
So, now that you've seen the most concise, here's the least concise (but still equivalent), which you should use only if your dialect is extremely limited and doesn't recognize any of these shortcuts:
^[A-Za-z][A-Za-z0-9][0-9][0-9]$
I definitely prefer the former (more readable too, IMHO), but alas, sometimes people are forced to work with such restrictions.
精彩评论