Search code examples
javascriptregexcapturing-group

Regex pattern to validate string with multiple conditions


I'm trying to write a regex pattern that validates a string by meeting a number of requirements but I believe I have to apply conditions to a capture group which I don't fully understand even after looking at articles.

I'm looking to loosely confirm that a string has a valid file type at the end of it e.g. filename.png.

Using a string similar to above I would like to:

  • match the substring after the final full stop in the string
  • check that this substring is only comprised of letters and numbers
  • check that it is less than or equal to 5 characters long

I've found this post, How to limit a regex capturing group?, but don't know how I'd go about combining it into my pattern.

Currently I have /\.[^.]*(a-zA-Z0-9)*$/g which works for file.name.png but doesn't meet any of the other conditions and I don't know where I'd position {0,5}.

How would I go about isolating the substring and applying the second two conditions to it?


Solution

  • You could take

    /\.[a-z0-9]{0,5}$/i
    

    which looks for

    • a dot
    • up to five letters or digits
    • end of the string
    • case insensitive search