in reply to Why does this non-greedy match not work?

Making the .+ non-greedy doesn't change that the dot is perfectly willing to match any / in the inputs (since a dot just matches any (non-newline, by default) character). It's still going to start at the left-most "/" that it sees (the first character) and then start gobbling up one or more things-which-match-dot (which includes all the subsequent letters and "/"s) until it hits the end of the line. If you'd explicitly asked for things-which-are-not-"/" using [^/]+ instead you'd have had more luck (e.g. m{/ ([^/]+) $}x).

Of course this could just be a slight XY problem and you really want File::Basename or Path::Tiny instead . . .

The cake is a lie.
The cake is a lie.
The cake is a lie.

Replies are listed 'Best First'.
Re^2: Why does this non-greedy match not work? (updated)
by haukex (Archbishop) on Jun 29, 2020 at 19:07 UTC

    I agree entirely, and just wanted to add: a common misconception (one that I was guilty of myself sometimes, before being enlightened about it) is that a regex that doesn't start with ^ but ends with $ somehow changes the behavior of the regex engine to start looking at the end of the string - this isn't how it works, the regex engine always matches from left to right and stops at the first match it finds. A regex of "/foo/bar/baz" =~ m{/[^/]+$} will still cause the regex engine to attempt to match /foo and /bar before settling on /baz - you can see this in action at this link (JavaScript and a modern browser required) when you click the use re "debug"; button.

    Update: Corrected = to =~, thanks hippo!