【问题标题】:Pattern for characters that might be in the string可能在字符串中的字符的模式
【发布时间】:2014-04-09 12:56:06
【问题描述】:

我知道我应该使用string.match() 来执行此操作,但我无法匹配字符串中“可能”的字符,例如:

teststring = "right_RT_12" 

我可以轻松地做这样的事情:

string.match(teststring , 'righteye_RT_[0-9]+')

如果测试字符串的末尾总是有“_[0-9]+”,这很好,但可能会出现末尾没有数字的情况。我将如何在 Lua 中解决这个问题?

在 Python 中,我可以执行以下操作:

re.search("righteye_RT(_[0-9]+)?", teststring)

我认为这样的事情会起作用:

string.match(teststring, 'righteye_RT_?[0-9]+?')

但它没有。结果 = nil

但是,以下方法确实有效,但只能找到第一个数字:

string.match(teststring, 'righteye_RT_?[0-9]?')

【问题讨论】:

    标签: string lua lua-patterns


    【解决方案1】:

    ? 只能用于 Lua 模式中的一个字符。您可以使用or 来匹配两种模式:

    local result  = string.match(teststring , 'righteye_RT_%d+') 
                 or string.match(teststring , 'righteye_RT')
    

    请注意,or 运算符是短路的。所以它首先尝试匹配第一个模式,当且仅当它失败(返回nil)时,它才会尝试匹配第二个模式。

    【讨论】:

    • 我喜欢这个。是否不可能像在 python 的正则表达式中那样在 1 行中执行此操作:"(righteye_RT_%d+ | righteye_RT)"
    • @iGwok Lua 模式不支持|,所以不,至少不是那样。
    【解决方案2】:

    试试这个:

    string.match(teststring, 'righteye_RT_?%d*$')
    

    注意字符串结尾锚$。没有它,%d* 将匹配空字符串,因此整个模式将匹配 righteye_RT_junk 之类的内容。

    【讨论】:

    • 这行得通,谢谢!但是为什么这行得通和 %d+?才不是?我以为 $ 只是在字符串末尾搜索字符?
    • %d+ 不起作用,因为它至少需要 一个 数字。
    • 我明白了,所以 %d* 也可以,但是 ?把它当作 %d* 扔掉了吗?还是不行。
    • @iGwok 但要小心。该模式匹配righteye_RT_string,这可能不合适。
    • 它匹配 "righteye_RT_" 但也匹配 "righteye_RT" 因为 ?
    猜你喜欢
    • 2020-09-06
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    • 2014-10-11
    • 2017-11-11
    • 1970-01-01
    相关资源
    最近更新 更多