Home > OS >  Regex: Only allow certain format within string
Regex: Only allow certain format within string

Time:01-29

I am using regex to validate input within a Google form, the input value should only contain the following formats SSDC ,SSFW , SS, HR, TR. For example SSDC66765 should work but SSCD or SSTY should not. I have tried to use the following regex

^[A-ZA-Z]{2,4}\d{3,4}$

But this does not limit to the following input SSDC ,SSFW , SS, HR, TR

CodePudding user response:

You could shorten it to an alternation, and not that SSDC66765 has 5 digits so the quantifier can be {3,5} instead (or adjust to your needs)

^(?:SS(?:FW|DC)?|[HT]R)\d{3,5}$

The pattern matches:

  • ^ Start of string
  • (?: Non capture group
    • SS(?:FW|DC)? Match either SS SSFW or SSDC
    • | Or
    • [HT]R Match either HR or TR
  • ) Close non capture group
  • \d{3,5} Match 3 - 5 digits
  • $ End of string

Regex demo

  •  Tags:  
  • Related