意外的Lua模式匹配结果 [英] Unexpected lua pattern matching result

查看:83
本文介绍了意外的Lua模式匹配结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下代码:

local function getParentPath(_path)

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

end

print(getParentPath(path))

对于路径="C://data//file.text",我得到:

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

C://data // file.text

但是对于路径="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?

推荐答案

问题是,第一个.+贪婪地匹配,并抢占了最后一个\的所有内容,然后回溯.然后,一个\可以与[\\/]匹配,因此第一组具有一个反斜杠,第二组具有第二个反斜杠.

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.

您可以通过使用

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

请参见 IDEONE演示

说明:

  • ^-字符串开头
  • (.-)-尽可能少的字符(与-量词的延迟匹配)
  • ([/\\]+)-1+ /\
  • ([^/\\]+)-/\
  • 以外的1个以上字符
  • $-字符串结尾
  • ^ - start of string
  • (.-) - any characters but as few as possible (lazy matching with - quantifier)
  • ([/\\]+) - 1+ / or \
  • ([^/\\]+) - 1+ characters other than / and \
  • $ - end of string

这篇关于意外的Lua模式匹配结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆