Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected lua pattern matching result

For the following code:

local function getParentPath(_path)

    pattern = "(.+)([/\\][/\\])(.+)"
    i,j,k = string.match(path,pattern)
    return i,j,k

end

print(getParentPath(path))

For path = "C://data//file.text", I get:

C://data // file.text

But For path = "C:\data\file.text", I get:

nil nil nil

I am looking for a pattern which woks for both. Any suggestions?

like image 443
tanzil Avatar asked Feb 07 '23 10:02

tanzil


1 Answers

The problem is that the first .+ matches greedily and grabs all up to the last \ and then backtracks. Then, one \ can be matched with [\\/], and thus the first group has one backslash, and the second has got the second.

You can fix it by using

pattern = "^(.-)([/\\]+)([^/\\]+)$"

See IDEONE demo

Explanation:

  • ^ - start of string
  • (.-) - any characters but as few as possible (lazy matching with - quantifier)
  • ([/\\]+) - 1+ / or \
  • ([^/\\]+) - 1+ characters other than / and \
  • $ - end of string
like image 58
Wiktor Stribiżew Avatar answered Feb 14 '23 23:02

Wiktor Stribiżew