dimButTries
dimButTries

Reputation: 886

matching a string between 2 nth positions

I am trying to extract the text between the 3rd and 4th slash from a url.

I have followed 2 or 3 posts on SO to achieve this and I can now select all slashes. But not targeting the 4th and 5th.

(?:[\/])
domain.com/dirone/dirtwo/prd/12345

However, I am trying to now select the 3rd and 4th slashes, using information from the posts.

(?:[\/]).{4}

But this selects 4 characters after every slash slash. Which is not what I need.

I understand from a very helpful post, once I can extract the slashes, I need something similar to this:

(?<=\[)(.*?)(?=\])

I am sure I am absolutely doing something nonsensical however, I am struggling to stitch together the intel from various posts to get even close to the success criteria.

Any advice would be very much welcomed.

Upvotes: 0

Views: 57

Answers (1)

alex-dl
alex-dl

Reputation: 862

If the regex flavor supports variable length lookbehinds, you could use following regex:

(?<=(?:[^\/]+\/){3})[^\/]+(?=\/)

Demo: https://regex101.com/r/ReGppA/1/

  • (?<=(?:[^\/]+\/){3}) positive lookbehind, match 3 times some text and a slash
  • [^\/]+ the text between the 3th and 4th slash
  • (?=\/) positive lookahead, the 4th slash

To match between 2nd and 3th:

(?<=^(?:[^\/]+\/){2})[^\/]+(?=\/)

Demo: https://regex101.com/r/zdyODD/1/

Upvotes: 2

Related Questions