我的环境:
os
和其他几个包,将允许访问本地文件系统,shell命令或类似的东西,因此,所有的功能必须在Lua本身(只)来实现。我需要写一个返回true
如果输入的字符串的字母和数字作为一个整体词重复一次或多次以任意顺序相匹配的功能,并可以在整个匹配字符串的开头或结尾有标点符号。我在同样的意义作为PCRE字边界\b
使用“整词”。
为了验证这个想法,这是一个使用LuLpeg的re
模块不正确的尝试;这似乎与负向前看符号而不是消极lookbehinds工作:
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"
,一句话:tv
,返回值:true
"I'd"
,一句话:d
,返回值:false
"tv"
,一句话:tv
,返回值:true
" tvtv! "
,一句话:tv
,返回值:true
" epon "
,一句话:nope
,返回值:false
" eponnope "
,一句话:nope
,返回值:false
"atv"
,一句话:tv
,返回值:false
如果我有一个完整的PCRE正则表达式库我能做到这一点很快,但我不,因为我不能链接到C,我还没有发现PCRE或类似的任何纯Lua中实现。
我不能肯定,如果LPEG具有足够的灵活性(使用LPEG直接或通过其re
模块)做我想做什么,但我敢肯定,内置的Lua函数不能做我想做的,因为它可以”吨处理重复的字符序列。 (tv)+
不Lua的内置string:match
功能和类似的工作。
有趣的资源我已经冲刷揣摩如何做到这一点,没有用:
Lua的模式是足够强大的。 这里不需要LPEG。
这是你的函数
function f(input, word)
return (" "..input:gsub(word:gsub("%%", "%%%%"), "\0").." "):find"%s%p*%z+%p*%s" ~= nil
end
这是功能测试
for _, t in ipairs{
{input = " one !tvtvtv! two", word = "tv", return_value = true},
{input = "I'd", word = "d", return_value = false},
{input = "tv", word = "tv", return_value = true},
{input = " tvtv! ", word = "tv", return_value = true},
{input = " epon ", word = "nope", return_value = false},
{input = " eponnope ", word = "nope", return_value = false},
{input = "atv", word = "tv", return_value = false},
} do
assert(f(t.input, t.word) == t.return_value)
end
我认为,因为%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
因为香草re
没有办法产生lpeg.B
模式是有些复杂。
下面是使用lpeg
一个lpeg.B
版本。 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