Martin Schmidt
Martin Schmidt

Reputation: 13

Regex to match part of URL

I'm new here and also new to regular expressions.

I'm looking for a regex rule to match first part of string like:

  1. start/a/preend/end
    • start/a
  2. start/a/xyz/preend/end
    • start/a
  3. start/a/b/preend/end
    • start/a/b
  4. start/a/b/xyz/preend/end
    • start/a/b
  5. start/a/b/c/preend/end
    • start/a/b/c
  6. start/a/b/c/xyz/preend/end
    • start/a/b/c

start is static word, end is static word, xyz is static word which may or may not be there, preend is variable word, but it is always there before end, a,b,c are variable words

Is such regex rule possible? I was only able to get version with the word "xyz" working or the version without the word "xyz" working, but I was not able to figure out universal rule.

I started with this: (.*)\/[^\/]*\/end$ then experimented with (xyz)? but haven't found universal rule.

Thank you in advance for any help and clues.

Upvotes: 1

Views: 1585

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89639

You can use a non-greedy quantifier *? and a lookahead assertion (?=...) to test forward. This way the non-greedy quantifier will take characters one by one until the subpattern in the lookahead succeeds:

^start/.*?(?=/xyz/|/[^/]*/end$)

demo

(Depending on the pattern delimiters if any, you may have to escape the slashes)

Upvotes: 1

Related Questions