Home > Net >  Extract string between forward slashes using regex
Extract string between forward slashes using regex

Time:06-22

I have a url pattern that takes the following form:

  1. https://www.facebook.com/foo123/photos/1234/
  2. https://www.facebook.com/foo123/photos/a.123/1234/

In this case I need to extract string after /photos/

eg:

  1. In case 1 the valid string is 1234
  2. 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 /.
  • Related