I need to write a regular expression to verify if a file input follows a rule:
A111B2_3_C.exe
in which:
- A: compulsory, it must be a’A’
- 111: compulsory, it is a natural number
- B: compulsory, it must be a’B’
- 2: compulsory, it is in range from 1->6
- _: compulsory, it must be ‘_’
- 3: compulsory, it must be a nature number
- _: optional if C followed, it must be ‘_’
- C: optional, C is a natural number
- .exe: is the end extension of the file
It should be accepted this one: A111B2_3_.exe as well. but A111B2_3_0.exe is not accepted. the number after 3_ must be greater than 0.
Thanks in advance.
It’s a bit hard to understand your requirements, but here’s a regex that should do what you want:
Explanation:
A— The letter ‘A’\d+— 1 or more numbersB— The letter ‘B’[1-6]— A single number: 1, 2, 3, 4, 5, or 6_— An underscore\d+— 1 or more numbers(_\d+)?— Optionally, an underscore followed by 1 or more numbers\.— A periodexe— The letters ‘exe’Edit: In response to your comments, here is a regex that will also accept
A111B2_3_.exe:I changed the last
\d+(one or more numbers) to\d*(zero or more numbers).Edit 2: Now I’ve changed
\d*to([1-9]\d*)?. What that means is left as an exercise to the reader.