Search code examples
regexnumbersletter

Regex for first eight letters and last number


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.


Solution

  • 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