【问题标题】:lua match repeating patternlua匹配重复模式
【发布时间】:2020-10-27 19:44:12
【问题描述】:

我需要以某种方式将模式封装在 lua 模式匹配中,以在字符串中找到该模式的整个序列。我这是什么意思。 例如我们有这样的字符串: "word1,word2,word3,,word4,word5,word6, word7," 我需要匹配第一个单词序列,后跟逗号 (word1,word2,word3,)

在 python 中我会使用这种模式"(\w+,)+",但在 lua 中类似的模式(如(%w+,)+)只会返回nil,因为 lua 模式中的括号意味着完全不同的东西。

我希望你现在能看到我的问题。 有没有办法在 lua 中做重复模式?

【问题讨论】:

    标签: lua lua-patterns


    【解决方案1】:

    word4,word5,word6 word7, 应该发生什么而言,您的示例不太清楚

    这会给你任何逗号分隔的单词序列,没有空格或空位。

    local text = "word1,word2,word3,,word4,word5,word6,       word7,"
    -- replace any comma followed by any white space or comma
    --- by a comma and a single white space
    text = text:gsub(",[%s,]+", ", ")
    -- then match any sequence of >=1 non-whitespace characters
    for sequence in text:gmatch("%S+,") do
      print(sequence)
    end
    

    打印

    word1,word2,word3,
    word4,word5,word6,
    word7,
    

    【讨论】:

      【解决方案2】:

      如果您可以使用 LPeg,您可以轻松地做到这一点:

      local lpeg = require "lpeg"
      local str = "word1,word2,word3,,word4,word5,word6,       word7,"
      local word = (lpeg.R"az"+lpeg.R"AZ"+lpeg.R"09") ^ 1
      local sequence = lpeg.C((word * ",") ^1)
      
      print(sequence:match(str))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-19
        • 2019-03-29
        • 2013-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-16
        • 2015-07-02
        相关资源
        最近更新 更多