4

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

Kojof
  • 429
  • 7
  • 15
  • 23
  • 5
    Use of `{1}` is pretty much redundant in a regular expression. – Andy E Jul 15 '10 at 23:28
  • 1
    @Andy: "but explicit is better than implicit!" - I'm just kidding, of course. Or maybe I'm not. See also http://stackoverflow.com/questions/3032593/using-explicitly-numbered-repetition-instead-of-question-mark-star-and-plus – polygenelubricants Jul 16 '10 at 10:04
  • 1
    @poly: I suppose you could call it a preference, but I think use of redundant idioms in a language often signifies either a lack of understanding or fear of a lack of understanding for your co-workers. Or maybe I don't. ;-) – Andy E Jul 16 '10 at 10:58

3 Answers3

5

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
  • 28,904
  • 13
  • 79
  • 85
  • Without the start `^` and end `$` matches, this would match part of a string like `abcd123456789` – Andy E Jul 15 '10 at 23:30
5

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
  • 338,112
  • 86
  • 474
  • 445
2

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
  • 3,918
  • 3
  • 25
  • 30
  • +1 Good point, but depends on whether or not the particular dialect of regex supports named character classes. (OP doesn't specify) – Stephen P Jul 16 '10 at 00:52