I have a url pattern that takes the following form:
In this case I need to extract string after /photos/
eg:
- In case 1 the valid string is 1234
- in case 2 the valid string is 1234
I drafted the the following regex but it fails on case 2
\/photos\/([^\/\?] )
so essentially grabbing everything after /photos/ followed by / ?
I need a simple regex that can also work in case 2
so the logic is:
the string is either found after /photos/ or one level after /photos/. The string only contains digits. If the string if found after /photos/ it would end with /. if it is found one level after /photos/ it would also end with /
CodePudding user response:
You can extract the digit chunk after any chars other than /
, ?
and digits:
\/photos\/(?:.*?\/)?(\d )(?![^\/])
See the regex demo.
Details:
\/photos\/
- a/photos/
string(?:.*?\/)?
- an optional sequence of any zero or more chars as few as possible and then a/
char(\d )
- Group 1: one or more digits(?![^\/])
- end of string or/
.