2

Please help me compose a working regular expression. Conditions:

  1. There can be a maximum of 9 characters (from 1 to 9).
  2. The first eight characters can only be uppercase letters.
  3. The last character can only be a digit.

Examples:

Do not match:

  • S3
  • FT5
  • FGTU7
  • ERTYUOP9
  • ERTGHYUKM

Correspond to:

  • E
  • ERT
  • RTYUKL
  • VBNDEFRW3

I tried using the following:

^[A-Z]{1,8}\d{0,1}$

but in this case, the FT5 example matches, although it shouldn't.

anubhava
  • 761,203
  • 64
  • 569
  • 643

3 Answers3

4

You may use an alternation based regex:

^(?:[A-Z]{1,8}|[A-Z]{8}\d)$

RegEx Demo

RegEx Details:

  • ^: Start
  • (?:: Start non-capture group
    • [A-Z]{1,8}: Match 1 to 8 uppercase letters
    • |: OR
    • [A-Z]{8}\d: Match 8 uppercase letters followed by a digit
  • ): End non-capture group
  • $: End
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

You might also rule out the first 7 uppercase chars followed by a digit using a negative lookhead:

^(?![A-Z]{1,7}\d)[A-Z]{1,8}\d?$
  • ^ Start of string
  • (?![A-Z]{1,7}\d) Negative lookahead to assert not 1-7 uppercase chars and a digit
  • [A-Z]{1,8} Match 1-8 times an uppercase char
  • \d? Match an optional digit
  • $ End of string

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
1

With a regex engine that supports possessive quantifiers, you can write:

^[A-Z]{1,7}+(?:[A-Z]\d?)?$

demo

The letter in the optional group can only succeed when the quantifier in [A-Z]{1,7}+ reaches the maximum and when a letter remains. The letter in the group can only be the 8th character.

For the .net regex engine (that doesn't support possessive quantifiers) you can write this pattern using an atomic group:

^(?>[A-Z]{1,7})(?:[A-Z]\d?)?$
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125