tags:

views:

213

answers:

3

I need a regular expression to allow the user to enter an alphanumeric string that starts with a letter (not a digit).

+1  A: 

I think this should do the work:

^[A-Za-z][A-Za-z0-9]*$
Michał Niklas
Why did you include the start tag but not the end? I would have thought you'd either leave them both off (which will work in the calls that match an entire line anyway) or put them both on (which will work in either the entire-line-match or string-match calls).
paxdiablo
OK. Added. You are right.
Michał Niklas
A: 

You're looking for a pattern like this:

^[a-zA-Z][a-zA-Z0-9]*$

That one requires one letter and any number of letters/numbers after that. You may want to adjust the allowed lengths.

ojrac
thank u Mr.ojrac it is working
Surya sasidhar
+6  A: 

This should work in any of the RE engines. There is a nicer syntax in the PCRE world but I prefer mine to be able to run anywhere:

^[A-Za-z][A-Za-z0-9]*$

Basically, the first character must be alpha, followed by zero or more alpha-numerics. The start and end tags are there to ensure that the whole line is matched. Without those, you may match the AB12 of the "@@@AB12!!!" string.

Full explanation:

^            start tag.
[A-Za-z]     any one of the upper/lower case letters.
[A-Za-z0-9]* any one of the upper/lower case letters or digits,
             repeated zero or more times.
$            end tag

Update:

As Richard Szalay rightly points out, this is ASCII only (or, more correctly, any encoding scheme where the A-Z, a-z and 0-9 groups are contiguous) and only for the "English" letters.

If you want true internationalized REs (only you know whether that is a requirement), you'll need to use one of the more appropriate RE engines, such as the PCRE mentioned above, and ensure it's compiled for Unicode mode. Then you can use "characters" such as \p{L} and \p{N} for letters and numerics respectively. I think the RE in that case would be:

^\p{L}[\pL\pN]*$

but I'm not certain. I've never used REs for our internationalized software. See here for more than you ever wanted to know about PCRE.

paxdiablo
ya it is working Mr.Paxdiablo thank a lot
Surya sasidhar
FYI, this syntax is limited to the ASCII character set.
Richard Szalay