Regular Expressions Help

I am trying to create a regular expression to help me validate a particular string that users will be passing into my application. I thought I had it figured out until I found a few test cases that my expression gave a false positive for. Here are the details:

  1. The first six characters will be letters or spaces.
  2. The first character must be a letter.
  3. If the first six characters are not all letters, then the rest of the six are padded with spaces.

Here are some examples of valid strings:


GHIJK 0123
LMNO  0123
PQR   0123
ST    0123
U     0123

So I quickly whipped up the below expression to validate these strings:


The problem is this can create false positives because I am not properly meeting requirement number 3. Here are some strings that cause false positives:


ABCD F0123
GHI JL0123
MN PQR0123
S UVWX0123

I’m not the best at regular expressions so I am kind of stumped as to how to proceed. How do I check the first six characters so that they are letters until a space is found and then it is padded until it reaches 6 characters. Thank you in advance for your help.

I can’t think of a way to directly check for letters with trailing spaces to pad out to the specific length without checking each combination separately such as

^([a-zA-Z]     )|([a-zA-Z]{2}    )|([a-zA-Z]{3}   )|(a-zA-Z){4}  )|([a-zA-Z){5} )|([a-zA-Z]{6})\\d{4}$

Alternatively testing two expressions separately would be shorter.

^[a-zA-Z]{1,6} {0,5}\\d{4}$
^[a-zA-Z ]{6}\\d{4}$

the first checks the spaces are after the letters while the second checks the total length.

Thank you for your reply, felgall. The example you gave was perfect. I was able to finish my validation code today. Thank you very much for your help! :slight_smile: