我有以下 anchor 字符串(我想在其中更改 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中的每个元素进行迭代并每次处理该字符串,但我的直觉告诉我,万一字符串非常大和/或替换表变得很大,这个方法的性能会很差。
因此,我认为最好可以执行以下操作:应用正则表达式来查找所有匹配项,为每个匹配项获取一个迭代器,并将每个匹配项替换为其在 replacementTable 中的值。
这样的东西会很棒(用 Javascript 编写,因为我还不知道如何在 Lua 中编写 lambda):
var newString = patternReplacement(s1, '<a[^>]* href="([^"]*)"', function(match) { return replacementTable[match] })
其中第一个参数是字符串,第二个参数是正则表达式,第三个参数是为每个匹配执行以获取替换的函数。这样我认为 s1 被解析一次,效率更高。
在Lua中有什么办法可以做到这一点吗?
最佳答案
在您的示例中,这个简单的代码有效:
print((s1:gsub("%w+",replacementTable)))
重点是 gsub
已经接受替换表。
关于regex - 如何替换 lua "in a single pass"中字符串的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40746062/