3

What is the regex that matches these examples(6 characters, first is a letter, others are numbers):

u78945 - valid
s56123 - valid
456a12 - invalid
78561d - invalid
1234567 - invalid

i don't know if regular expressions are the same for every programming language. I need it for Regular Expression Validator control using VB ASP.NET.

phalanx
  • 487
  • 5
  • 14
  • 30

3 Answers3

5

Use this pattern:

^[a-z][0-9]{5}$

This will match any Latin letter (lower-case unless using case-insensitive matching) followed by 5 decimal digits.

Note: You could use \d instead of [0-9], but read this for an explanation about why they are different.

Community
  • 1
  • 1
p.s.w.g
  • 136,020
  • 27
  • 262
  • 299
  • Thank you @p.s.w.g I wasn't aware of the unicode characters caught by \d. I'll probably still use it, but it is good to be aware ;) – Andy G Jul 12 '13 at 23:45
  • @AndyG Both are valid, depending on what exactly you need. If validating user input, I'd prefer `\d` for international support. If really want to ensure that `0-9` are the only valid values, that's probably what you should use. – p.s.w.g Jul 12 '13 at 23:47
2
[a-zA-Z]\d{5}

If you are searching explicitly from the beginning of the line use ^

^[a-zA-Z]\d{5}

and append $ for the end of the line.

Andy G
  • 18,518
  • 5
  • 42
  • 63
0
^[a(?i)-z(?i)]\d{5}$

The (?i) code enables the expression to accept any letter without case-sensitivity. The \d{5} looks for a sequence of numbers whose length is exactly 5.

pcnThird
  • 2,304
  • 1
  • 16
  • 31