如何在 Lua "单次处理" 中替换字符串的部分内容?

我有以下锚点字符串(我想更改 href 内容)和一个 Lua 替换表,该表告诉该替换哪个单词:

s1 = '<a href="word1"></a><a href="word2"></a><a href="word3"></a><a href="word1"></a><a href="word5"></a><a href="word2"></a><a href="word3"><a href="word7"></a>'

replacementTable = {}
replacementTable["word1"] = "potato1"
replacementTable["word2"] = "potato2"
replacementTable["word3"] = "potato3"
replacementTable["word4"] = "potato4"
replacementTable["word5"] = "potato5"

预期结果应为:

<a href="potato1"></a><a href="potato2"></a><a href="potato3"></a><a href="potato1"></a><a href="potato5"></a><a href="potato2"></a><a href="potato3"><a href="word7"></a>

我知道我可以遍历 replacementTable 中的每个元素并每次处理字符串,但我的直觉告诉我,如果字符串非常大和/或替换表变得大,这种方法的性能将表现不佳。

因此,我认为最好的方法是:应用正则表达式查找所有匹配项,获取每个匹配项的迭代器,并将每个匹配项替换为其在替换表中的值。

像这样的东西将很棒(使用 JavaScript 编写它,因为我还不知道如何在 Lua 中编写 Lambda):

var newString = patternReplacement(s1, '<a[^>]* href="([^"]*)"', function(match) { return replacementTable[match] })

其中第一个参数是字符串,第二个参数是正则表达式,第三个参数是一个函数,用于获取替换中的每个匹配项。这样,我认为 s1 只需解析一次,更加高效。

有没有办法在 Lua 中实现这一点?

点赞
用户2316068
用户2316068

最终,对我起作用的解决方案如下:

local updatedBody = string.gsub(body, '(<a[^>]* href=")(/[^"%?]*)([^"]*")', function(leftSide, url, rightSide)
    local replacedUrl = url
    if (urlsToReplace[url]) then replacedUrl = urlsToReplace[url] end
    return leftSide .. replacedUrl .. rightSide
end)

它排除了任何查询字符串参数,只给出了 URI。我知道使用正则表达式解析 HTML 主体是不好的想法,但对于我需要大量性能的情况,它的表现更快,只是完成了工作。

2016-11-22 15:58:49
用户107090
用户107090

在你的例子中,这个简单的代码很有效:

print((s1:gsub("%w+",replacementTable)))

关键在于 gsub 已经接受了一个替换表。

2016-11-22 16:59:42