rickchristie
rickchristie

Reputation: 1720

Use a character to look ahead, but only when it exists

Suppose I have these line:

/path-to-something/section/resource?var=name
/path-to-something/section/resource

I want to use regular expression to capture the text between /path-to-something/ and the ? sign. So for both cases, I want the output to be:

section/resource

The farthest I can go is to use this regex:

(?<=/path-to-something/).+(?=\?)

But it fails for the second case (where the URL doesn't have the ? sign):

section/resource
[no match]

Is there a way to do something like this in Regular Expression? I know I can do this without regular expression, but I wanted to know if this is possible to do in regex.

Upvotes: 1

Views: 73

Answers (1)

Cameron
Cameron

Reputation: 98756

How about:

(?<=/path-to-something/)[^?]+

Upvotes: 2

Related Questions