Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to regex a string - length 8, first character letter and remaining numeric

Tags:

I am trying to create a RegEx to match a string with the following criterion

  • Length 8
  • First character must be a letter a-z or A-Z
  • The remaining 7 must be numeric 0-9

examples

  • a5554444
  • B9999999
  • c0999999

This is what I have so far

^[0-9]{8}$

What am I missing to check the first character? I tried

^[a-zA-Z][0-9]{8}$

but that's not working.

like image 295
Saif Khan Avatar asked Oct 05 '12 00:10

Saif Khan


People also ask

What does \b mean in regex?

The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).

What does \\ mean in regex?

The backslash character (\) in a regular expression indicates that the character that follows it either is a special character (as shown in the following table), or should be interpreted literally. For more information, see Character Escapes. Escaped character. Description. Pattern.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.

How do you range a character in regex?

To show a range of characters, use square backets and separate the starting character from the ending character with a hyphen. For example, [0-9] matches any digit. Several ranges can be put inside square brackets. For example, [A-CX-Z] matches 'A' or 'B' or 'C' or 'X' or 'Y' or 'Z'.


1 Answers

I think this is what you want:

^[a-zA-Z][0-9]{7}$

the {...} metacharacter only matches the most previous pattern which in your case is [0-9]. the regex interpretation is as follows:

  1. start at the beginning of the string (^)
  2. match any character a-z or A-Z ([a-zA-Z]) in the first spot only one time
  3. match any character 0-9 starting at the second spot ([0-9])
  4. the preceding pattern mentioned in step 3 of [0-9] must exist exactly 7 times ({7})

When you put {8} as per your original question, you'll assume a string length total of 9: the first character being alphabetic case insensitive and the remaining 8 characters being numeric.

like image 145
CrazyCasta Avatar answered Oct 20 '22 04:10

CrazyCasta