Regular expressions will always try to match left to right. Even though .+?
is non-greedy, the regex will still try to match from the beginning of the string if possible and only advance the starting position when the match fails.
You have a couple of options to fix this:
- Include a greedy match at the beginning of the regex so that your match will always start as far into the string as possible, and use a capturing group to grab what you want. The regex here might looks something like
/.*(\/.+?)$/
, and then you would get/file
as the contents in the first capturing group. - Change the regex so that the
.+?
can't match any additional/
, so it would be/\/[^\/]+$/
.