我的环境:
os和其他几个允许访问本机文件系统、shell命令或诸如此类的包,因此所有功能都必须在Lua本身中实现(仅限于)。我需要编写一个函数,如果输入字符串匹配一个字母和数字的任意序列,整个单词重复一次或多次,并且可能在整个匹配子字符串的开头或结尾有标点符号,则需要编写返回true的函数。我使用“整体单词”的含义与PCRE单词边界\b的含义相同。
为了演示这个想法,下面是一个不正确的尝试,它使用了re模块的LuLpeg;它似乎适用于负的外观,而不是负的查找
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,返回值: true"I'd",word: d,返回值: false"tv",word: tv,返回值: true" tvtv! ",word: tv,返回值: true" epon ",word: nope,返回值: false" eponnope ",word: nope,返回值: false"atv",word: tv,返回值: false如果我有一个完整的PCRE regex库,我可以快速地做到这一点,但我不能这样做,因为我无法链接到C,而且我还没有找到任何纯的PCRE或类似的Lua实现。
我不确定LPEG是否足够灵活(直接使用LPEG或通过它的re模块)来做我想做的事情,但是我很确定内置的Lua函数不能做我想做的事情,因为它不能处理重复的字符序列。(tv)+不适用于Lua的内置string:match函数和类似功能。
我一直在搜索有趣的资源,试图找出如何做到这一点,但没有结果:
发布于 2019-02-04 10:21:50
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发布于 2019-02-04 06:52:04
我认为该模式不能可靠地工作,因为%s*[^%s]^0部分匹配一系列可选的间距字符和非空格字符,然后尝试匹配重复的单词,然后失败。在此之后,它不会在字符串中向后或向前移动,并试图在另一个位置匹配重复的单词。LPeg和re的语义与大多数正则表达式引擎的语义非常不同,即使看起来类似的东西也是如此。
这是一个re-based版本。模式只有一个捕获(重复字),所以如果找到了重复字,匹配返回一个字符串,而不是一个数字。
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
endhttps://stackoverflow.com/questions/54510033
复制相似问题