Skip to content
Advertisement

Generating RegEx pattern for a given string

I need to generate a RegEx pattern for a file name validation. But I am not used to RegEx pattern. I did try to generate patterns by using think link. I generated a pattern (^.*$)|(^.*i.*$) but it is not working as desired and got new pattern ^d+(?:_[A-Za-z]+)?$ from an answer but some new conditions are required which I have listed below.

My required validations are as follows :

  • 1234567890 => Valid
  • 1234567890_Alphabet => Valid, ‘_’ symbol is valid, other symbol as well as white space characters are invalid.
  • 1234567890 – Alphabet => Invalid
  • 1234567890alphabet => Invalid

New conditions :

  • 11244422_134444_john => Valid
  • 1234322_1234431 john => Invalid
  • 1234222_134322-john => Invalid
  • 12422344_12453222 => Valid

Some other validations :

  • The string should start as numeric but not alphabet. i.e. Numeric only
  • Underscore(_) preceded by numbers.

Advertisement

Answer

Start by matching the digits, and optionally match an underscore and ASCII chars A-Za-z.

^d+(?:_d+)?(?:_[A-Za-z]+)?$
  • ^ Start of string
  • d+ Match 1+ digits
  • (?:_d+)? Optionally match _ and 1+ digits
  • (?:_[A-Za-z]+)? Optionally match _ and 1+ times any of A-Za-z
  • $ End of string

Regex demo

Advertisement