【问题标题】:Lua string.gsub text between patternLua string.gsub 模式之间的文本
【发布时间】:2014-05-19 03:09:03
【问题描述】:

如何在 Lua 中提取模式之间的文本。例如

s="this is a test string. <!2014-05-03 23:12:08!> something more"
  1. 我只需要日期/时间作为结果:2014-05-03 23:12:08
    print(string.gsub(s, "%&lt;!.-%!&gt;")) 不起作用
  2. 我需要所有没有日期/时间的文本,例如:"this is a test string. something more"

【问题讨论】:

  • 如果您可以确定文本中没有其他&lt;&gt;;使用%b 匹配:s:gsub( '%b&lt;&gt;', '' )

标签: string lua lua-patterns


【解决方案1】:

模式"&lt;!.-!&gt;" 有效,但您需要使用string.match 来获取日期/时间部分:

 print(string.match(s, "<!(.-)!>"))

请注意,您无需在模式中转义 !&lt;。当然,逃避它们并不是错误。

要获取不带日期/时间部分的字符串,请将其替换为空字符串:

local result = string.gsub(s, "<!.-!>", "")
print(result)

您还可以扩展模式.- 以验证更多日期/时间的格式:

result = string.gsub(s, "<!%d%d%d%d%-%d%d%-%d%d%s+%d%d:%d%d:%d%d!>", "")

【讨论】:

  • 太棒了! =)
猜你喜欢
  • 2014-11-15
  • 1970-01-01
  • 2014-10-06
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
  • 1970-01-01
  • 2015-03-13
  • 1970-01-01
相关资源
最近更新 更多