Unexpected lua pattern matching result

这一生的挚爱 提交于 2019-12-12 12:19:21

问题


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?


回答1:


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



回答2:


It is perfectly expected. First greedy (.+) matches as many symbols as it can without breaking following patterns - i.e. everything up to very last slash that is necessary to make ([/\\]+) match.



来源:https://stackoverflow.com/questions/36204988/unexpected-lua-pattern-matching-result

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!