Home > Net >  Regex to match multiple subdirectories in a URL
Regex to match multiple subdirectories in a URL

Time:10-20

Is it possible to write a regex to capture sub paths that come after https://localhost:443/one/12345678/two/12345678? Given the URL below, I would like to capture a, b, c, and d:

https://localhost:443/one/12345678/two/12345678/a/b/c/d?p1=1&p2=2&p3=3

This is what I have so far, but it only captures a:

[\w\W]*one\/\w{8}\/two\/\w{8}(?:\/?([\w]))

CodePudding user response:

You can use

(?<=/one/\w{8}/two/\w{8}/[^?#]*?)[^/?#] 

See the regex demo.

Details:

  • (?<=/one/\w{8}/two/\w{8}/[^?#]*?) - a positive lookbehind that matches a location that is immediately preceded with /one/, then eight word chars (\w{8}), /two/, another eight word chars, / and then any zero or more chars other than ? and # as few as possible (with [^?#]*?)
  • [^/?#] - one or more chars other than a /, # and ?.
  • Related