【问题标题】:How to implement string.rfind in Lua如何在 Lua 中实现 string.rfind
【发布时间】:2013-06-27 12:44:07
【问题描述】:

在 Lua 中只有 string.find,但有时需要 string.rfind。例如,解析目录和文件路径,如:

fullpath = "c:/abc/def/test.lua"
pos = string.rfind(fullpath,'/')
dir = string.sub(fullpath,pos)

这样的string.rfind怎么写?

【问题讨论】:

    标签: string lua lua-patterns


    【解决方案1】:

    你可以使用string.match

    fullpath = "c:/abc/def/test.lua"
    dir = string.match(fullpath, ".*/")
    file = string.match(fullpath, ".*/(.*)")
    

    在这个模式中,.* 是贪婪的,所以它会在匹配 / 之前尽可能多地匹配

    更新

    正如@Egor Skriptunoff 指出的那样,这样更好:

    dir, file = fullpath:match'(.*/)(.*)'
    

    【讨论】:

    • dir, file = fullpath:match'(.*/)(.*)'
    【解决方案2】:

    Yu & Egor 的回答很有效。使用 find 的另一种可能性是反转字符串:

    pos = #s - s:reverse():find("/") + 1
    

    【讨论】:

    • 这给出了相同的结果:pos = s:match'.*()/'
    • 请注意,通常反转字符串也会反转您正在寻找的子字符串。
    猜你喜欢
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 2011-12-08
    • 2020-10-11
    • 2014-01-13
    • 2021-06-24
    • 1970-01-01
    • 2021-01-12
    相关资源
    最近更新 更多