OldGuy
OldGuy

Reputation: 109

How to build a REGEX pattern to verify an input field

I have an input search field that I need to edit with Regex, which I am terrible with. The field can be 1 to 6 characters. The first three characters, if provided, must be uppercase letters, the second three must be numeric. So the pattern I have is [A-Z]{3}[0-9]{3}, which appears to be working for all 6 characters. The kicker is at any point the user can end the string with an asterisk. So "ABC123" is fine. So is "AB*" or "ABC1*". "AB1*" is an error. And asterisk by itself is also not allowed.

I tried [A-Z*]{1-3}[0-9*]{0,3} but that allows "A**" and "AB1".

What do I need to do?

Upvotes: 1

Views: 92

Answers (1)

Aaron
Aaron

Reputation: 24812

The most straightforward way is to describe all possible strings, as an alternation of these sub-patterns :

  • [A-Z]\*
  • [A-Z]{2}\*
  • [A-Z]{3}\*
  • [A-Z]{3}[0-9]\*
  • [A-Z]{3}[0-9]{2}\*
  • [A-Z]{3}[0-9]{3}

With simple factorization you can reduce it to these sub-patterns :

  • [A-Z]{1,3}\*
  • [A-Z]{3}[0-9]{1,2}\*
  • [A-Z]{3}[0-9]{3}

Which gives us this final result : [A-Z]{1,3}\*|[A-Z]{3}[0-9]{1,2}\*|[A-Z]{3}[0-9]{3}.

Upvotes: 4

Related Questions