Corresponding regular expression URI

You must capture 3 elements from the requested URI.

The valid URI format will be as follows:

/users/{id}.{size}.{type} 

While id and size can be numbers. And the type can only be "jpg" or "png".

A twist is that size is optional. Therefore, another URI format would be:

 /users/{id}.{type} 

Valid examples are:

 /users/123.100.jpg /users/123.100.png /users/123.jpg /users/123.png 

Invalid examples:

 /users/asd.jpg /users/123.tiff /users/123..jpg /users/123..100..jpg /users/123..100.jpg /users/123.100 

Thanks.

+4
source share
2 answers

Try this regex. It retrieves id, size and type

Firstly, this regex confirms that the URL matches your actual pattern.

 \/users\/(\d+)(?:\.(\d+))?\.(jpg|png) 
  • Id: (?<=/)\d+
  • size: (?<=\.)\d+(?=\.) . Assumes the URL is built correctly.
  • Type:. .*(jpg|png)
+2
source

this regex should do the validation for you:

 /users/(\d+\.){1,2}(jpg|png) 

see example here: http://regexr.com?33vba

+1
source

All Articles