我的环境:
- Lua 5.1
- 绝对不能使用具有 native 组件(如 C .so/.dll)的库
- 我可以运行任意纯 Lua 5.1 代码,但我无法访问
os
和其他几个允许访问 native 文件系统、shell 命令或类似内容的包,因此所有功能必须在 Lua 本身(仅)中实现。 - 我已经设法拉入了 LuLpeg .我可能可以引入其他纯 Lua 库。
我需要编写一个函数,如果输入字符串匹配任意字母和数字序列作为重复一次或多次的完整单词,则返回 true
,并且整个匹配子串的开头或结尾可能有标点符号。我在与 PCRE 词边界 \b
相同的意义上使用“整个词”。
为了证明这个想法,这里是使用 LuLpeg 的 re
模块的错误尝试;它似乎适用于负面前瞻,但不适用于背后:
function containsRepeatingWholeWord(input, word)
return re.match(input:gsub('[%a%p]+', ' %1 '), '%s*[^%s]^0{"' .. word .. '"}+[^%s]^0%s*') ~= nil
end
这里是示例字符串和预期的返回值(引号的语法就像输入到 Lua 解释器中一样,而不是字符串的文字部分;这样做是为了使尾随/前导空格明显):
- 输入:
"one !tvtvtv!two"
, word:tv
, 返回值:真
- 输入:
“I'd”
,word:d
,返回值:假
- 输入:
"tv"
,word:tv
,返回值:真
- 输入:
"tvtv!"
,word:tv
,返回值:true
- 输入:
"epon"
,word:nope
,返回值:错误
- 输入:
"eponnope "
,词:nope
,返回值:错误
- 输入:
"atv"
,word:tv
,返回值:错误
如果我有一个完整的 PCRE 正则表达式库,我可以快速完成此操作,但我没有,因为我无法链接到 C,而且我还没有找到任何 PCRE 或类似的纯 Lua 实现。
我不确定 LPEG 是否足够灵活(直接使用 LPEG 或通过它的 re
模块)来做我想做的事,但我很确定内置的 Lua 函数可以'不要做我想做的事,因为它不能处理重复的字符序列。 (tv)+
不适用于 Lua 的内置 string:match
函数和类似函数。
我一直在寻找有趣的资源以试图找出如何做到这一点,但无济于事:
- http://www.inf.puc-rio.br/~roberto/lpeg/re.html
- http://www.lua.org/manual/5.2/manual.html#6.4.1
- http://lua-users.org/wiki/FrontierPattern (不幸的是,我的解释器不支持)
- http://lua-users.org/wiki/PatternsTutorial
- http://www.gammon.com.au/lpeg
- http://lua-users.org/wiki/StringRecipes
- how to check if a word appears as a whole word in a string in Lua
最佳答案
我认为该模式不能可靠地工作,因为 %s*[^%s]^0
部分匹配一系列可选的空格字符,后跟非空格字符,然后它会尝试匹配重复的单词并失败。之后,它不会在字符串中向后或向前移动,并尝试在另一个位置匹配重复的单词。 LPeg 和 re
的语义与大多数正则表达式引擎的语义非常不同,即使对于看起来相似的事物也是如此。
这是一个基于re
的版本。该模式只有一个捕获(重复词),因此如果找到重复词,匹配将返回一个字符串而不是数字。
function f(str, word)
local patt = re.compile([[
match_global <- repeated / ( [%s%p] repeated / . )+
repeated <- { %word+ } (&[%s%p] / !.) ]],
{ word = word })
return type(patt:match(str)) == 'string'
end
它有点复杂,因为 Vanilla re
没有办法生成 lpeg.B
模式。
这是一个使用 lpeg.B
的 lpeg
版本。 LuLPeg 也适用于此。
local lpeg = require 'lpeg'
lpeg.locale(lpeg)
local function is_at_beginning(_, pos)
return pos == 1
end
function find_reduplicated_word(str, word)
local type, _ENV = type, math
local B, C, Cmt, P, V = lpeg.B, lpeg.C, lpeg.Cmt, lpeg.P, lpeg.V
local non_word = lpeg.space + lpeg.punct
local patt = P {
(V 'repeated' + 1)^1,
repeated = (B(non_word) + Cmt(true, is_at_beginning))
* C(P(word)^1)
* #(non_word + P(-1))
}
return type(patt:match(str)) == 'string'
end
for _, test in ipairs {
{ 'tvtv', true },
{ ' tvtv', true },
{ ' !tv', true },
{ 'atv', false },
{ 'tva', false },
{ 'gun tv', true },
{ '!tv', true },
} do
local str, expected = table.unpack(test)
local result = find_reduplicated_word(str, 'tv')
if result ~= expected then
print(result)
print(('"%s" should%s match but did%s')
:format(str, expected and "" or "n't", expected and "n't" or ""))
end
end
关于regex - 在 Lua 5.1 中将可重复字符串匹配为 "whole word",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54510033/