1

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?

1
  • 1
    I need to edit with Regex, which I am terrible with -> regexr.com is your friend Commented Nov 8, 2016 at 15:46

1 Answer 1

4

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}.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow. Thanks! I would NEVER have put that together.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.