Search code examples
javascriptregexregex-greedy

Non-greed regex misunderstanding, /\/.*?$/ act like greed


I'm trying this in javascript

/\/.*?$/.exec('foo/bar/tar')[0]

I was expecting to get /tar as result but getting /bar/tar. As far as I understand non-greed regex would take the smallest match.

I'm circumventing this with myvar.split('/').reverse()[0] but I couldn't understand what is going wrong with the regex.


Solution

  • There is nothing wrong with the regex but the pattern \/.*?$ matches from the first forward slash until the end of the string non greedy.

    The dot matches any character except a newline and does not take a forward slash into account, so that will result in /bar/tar.

    If you want to match /tar, you could match a forward slash, followed by not matching anymore forward slashes using a negated character class and then assert the end of the string.

    \/[^\/]+$
    

    Pattern demo

    console.log(/\/[^\/]+$/.exec('foo/bar/tar')[0]);