user1735366
user1735366

Reputation: 53

Regex match specific URI

Need to capture 3 elements from the requested URI.

A valid format of the URI would be as follows:

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

Whereas id and size can be digits. And type can only be 'jpg' or 'png'.

The twist is that the size is optional. Hence the other format of the URI would be:

/users/{id}.{type}

Valid examples are as follows:

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

Invalid examples are as follows:

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

Thanks.

Upvotes: 5

Views: 2447

Answers (2)

user626607
user626607

Reputation:

Try this regex. It extracts the id, size and type

First, this regex validates that the url matches your valid pattern.

\/users\/(\d+)(?:\.(\d+))?\.(jpg|png)
  • Id: (?<=/)\d+
  • size: (?<=\.)\d+(?=\.). Assumes that the url is constructed in a valid manner.
  • type: .*(jpg|png)

Upvotes: 2

Kent
Kent

Reputation: 195219

this regex should do the validation for you:

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

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

Upvotes: 1

Related Questions