tags:

views:

57

answers:

3

hi,

can someone please help me to compose a regular expression to check an alphanumeric string is in a particular format.

First character must be a letter and the next 6 characters are numbers...eg x279833 or X279833 are both valid.

This is what i've come up with - ^[A-Za-z]{1}[0-9]{6}$

regards

+4  A: 

something like:

^[a-zA-Z]\d{6}$
  • [a-zA-Z] matches alpha chars
  • \d matches a numeric char
  • {6} will match 6 occurrences of the previous token, in this case 6 numeric chars
krock
Without the start `^` and end `$` matches, this would match part of a string like `abcd123456789`
Andy E
@Andy E, thanks added.
krock
+5  A: 

Yours should work just fine (you edited it in after I wrote this answer), but the {1} is completely unnecessary. You can shorten it a little to use \d instead of [0-9].

If you want to make sure the entire string is that format, use:

^[a-zA-Z]\d{6}$
Andy E
thanks a lot for clarifying.
Kojof
+2  A: 

I don't think I can say anything that hasn't already been considered except to think about international characters. If your first character can also be an alphabetic character from other character sets, you may want to use a predefined character class instead. In that case, you'd have something like this:

^[[:alpha:]]\d{6}$
bluesmoon
+1 Good point, but depends on whether or not the particular dialect of regex supports named character classes. (OP doesn't specify)
Stephen P