【问题标题】:lua not handling anchors in string.find or string.matchlua 不处理 string.find 或 string.match 中的锚点
【发布时间】:2016-09-04 03:27:38
【问题描述】:

这已经在Pattern in lua with anchors not matching 被问过,但是我有一个测试用例表明它似乎仍然不起作用:

patterns = {
    'a@b',
    '^a@b',
    'a@b.com',
    'my-a@b',
    'my-a@b.com',
    'a@b.com$',
    '^this-is-my-a@b.com',
    'this-is-my-a@b.com$',
    '^this-is-my-a@b.com$',
}

test = "this-is-my-a@b.com"

for _, pattern in ipairs(patterns) do
    print(pattern .. ": " .. test .. "\n\tfind: " .. (test:find(pattern) or 'nil') .. "\n\tmatch: " .. (test:match(pattern) or 'nil'))
    print(pattern .. ": " .. test .. "\n\tfind: " .. (string.find(test, pattern) or 'nil') .. "\n\tmatch: " .. (string.match(test, pattern) or 'nil'))
end

我做了单独的 test:findstring.find(test...) 只是为了确保没有恶作剧。

有人能告诉我如何让我的锚定模式发挥作用吗?

【问题讨论】:

  • lua版本是5.1.4
  • .- 是正则表达式上下文中的特殊字符。所以你需要逃避它们。

标签: lua anchor string-matching


【解决方案1】:

您使用的某些字符(如.-)在模式匹配中具有特殊含义,您需要将它们转义。例如,使用^this%-is%-my%-a@b%.comthis%-is%-my%-a@b%.com$ 应该会产生预期的结果。

【讨论】:

  • 我已经在那种情况下挣扎过,又被抓了!谢谢:)
猜你喜欢
  • 1970-01-01
  • 2012-02-23
  • 2017-03-01
  • 2011-11-05
  • 2013-06-04
  • 2017-08-08
  • 1970-01-01
  • 1970-01-01
  • 2014-08-04
相关资源
最近更新 更多