1

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.

2 Answers 2

2

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

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

6 Comments

thank you for the answer but I have some new conditions that I have added in the description. Can u suggest some changes for new condition ? I tried to modify your regex pattern but couldn't succeed.
@SudeepShakya Did you change the question?
I added few new conditions. New conditions : 11244422_134444_john => Valid, 1234322_1234431 john => Invalid, 1234222_134322-john => Invalid, 12422344_12453222 => Valid
@SudeepShakya Like this? ^\d+(?:_\d+)?(?:_[A-Za-z]+)?$ regex101.com/r/lJNYSc/1
I will try and verify it .
|
2
[0-9]+($|_[A-Za-z]+)

see https://regex101.com/r/X5BMJ1/1 for live example

Basically, you get numbers first, and that's it ($) or you require _ followed by letters

Comments

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.