【问题标题】:LUA String phrase matchLUA 字符串短语匹配
【发布时间】:2021-10-03 03:25:51
【问题描述】:

字符串:x11y22z33

我想用 1 个字符串和 2 个数字的 string.match 验证上述值

string.match(s,"/^\s{1}\d{2}\s{1}\d{2}\s{1}\d{2}")

我试过了,但是没用

【问题讨论】:

    标签: lua openresty


    【解决方案1】:

    Lua 有一个特定的语法:

    string.match(s,"(%a)(%d%d)(%a)(%d%d)(%a)(%d%d)")
    

    您可以在5.4.1 – Patterns章节中查看手册

    http://www.lua.org/manual/5.1/manual.html

    【讨论】:

      【解决方案2】:

      string.find() 也可以处理模式并为您提供位置...
      : 表示:数据类型“字符串”有string 元方法)

      do
      local str='not important important: x11y22z33 and ignore rest'
      local head,tail,a,b,c=str:find('(%a%d%d)(%a%d%d)(%a%d%d)')
      
      print(str:sub(head,tail))
      
      return head,tail,a,b,c
      end
      

      (没有错误处理)
      ...用string.sub()提取它
      输出和结果(返回)是...

      x11y22z33
      26  34  x11 y22 z33
      

      上面的例子还表明,string.find() 的结果在使用() 时被扩展。
      所以(%a)(%d+)(%a)(%d+)(%a)(%d+) 模式会产生 3 个键/值对。

      local head,tail,k1,x,k2,y,k3,z=str:find('(%a)(%d+)(%a)(%d+)(%a)(%d+)')
      ...
      return head,tail,k1,x,k2,y,k3,z 
      -- Puts out: 26 34 x 11 y 22 z 33
      -- And also works with x1024y3000z5
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-11
        • 1970-01-01
        • 1970-01-01
        • 2021-06-11
        • 2011-09-02
        • 1970-01-01
        相关资源
        最近更新 更多