Home > Software engineering >  Regex for first eight letters and last number
Regex for first eight letters and last number

Time:12-02

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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?)?$
  • Related