regex - 如何替换 lua "in a single pass"中字符串的一部分?

标签 regex string lua

我有以下 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/

相关文章:

c - Lua 和 C 结构

javascript - 这个函数可以用正则表达式重写吗?

java - 无法匹配我的正则表达式

java - 使用正则表达式java的字符串操作

php - 多字节 strtr() -> mb_strtr()

php - 关于strpos : how to get 2nd occurrence of a string?的问题

oop - 函数在构造函数内部调用时返回 nil

c++ - 如何通过 SWIG 将 lua 嵌入到 C++ 中

regex - 将数学表达式与正则表达式匹配?

python - 将字符串匹配到元组列表