StartingFromScratch
StartingFromScratch

Reputation: 628

Javascript RegEx to validate file name pattern

I need to validate file name with following pattern....

  1. File name(string) should not be null or empty
  2. File name(string) should have extension as .INI
  3. File name(string) should have "gen1" or "gen2" or "gen3"... genN where N has to be number.

We have already done the implementation with Javascript string functions but it looked little messy..

I am really interested in Validation-3 of "genN" which can be done more gracefully with RegEx

Upvotes: 0

Views: 1899

Answers (2)

Ry-
Ry-

Reputation: 224855

By "should have genN", do you mean:

  • Should be named gen#.ini?

    /^gen\d\.ini$/i
    
  • Should contain gen#?

    /^.*gen\d.*\.ini$/i
    

Also, if you want more than 0 to 9 in those, change \d to \d+. If you only want to accept 1 and onwards, [1-9]. Both these requirements? [1-9]\d*.


Here's a helpful picker that should make the right regular expression for you.

Upvotes: 2

ruakh
ruakh

Reputation: 183231

I agree, this sounds perfectly suited to regexes. Assuming that N has to be a positive decimal integer, and it can't have leading 0s, you can write:

/^gen[1-9][0-9]*\.INI$/

which means "start-of-string (^), followed by gen, followed by a digit in the range 1-9, followed by zero or more (*) digits in the range 0-9, followed by a literal dot (\.), followed by INI, followed by end-of-string ($)".

Upvotes: 0

Related Questions