[英]Lua pattern matching, repeating character
I'm a beginner at pattern matching.我是模式匹配的初学者。 I've learned that Lua's pattern matching is a little different from the standard, so I haven't been able to find a way to adapt regex solutions to this problem into Lua code.我了解到 Lua 的模式匹配与标准有点不同,因此我一直无法找到一种方法将针对此问题的 regex 解决方案调整到 Lua 代码中。
I'm trying to replace the longest substring of a repeating character in a string.我正在尝试替换字符串中重复字符的最长子字符串。
For example, in abbbccccc, it would find a, bbb, ccccc.例如,在 abbbbccccc 中,它会找到 a, bbb, ccccc。
This doesn't work, it just matches the whole string:这不起作用,它只匹配整个字符串:
string.gsub(inputString, "(.+)", function (n) return replace(n) end)
I can see how why it wouldn't work, but I can't find another way.我可以理解为什么它不起作用,但我找不到其他方法。
I know I could solve this problem easily using a loop, but I'm trying to get more practice with regular expressions and such.我知道我可以使用循环轻松解决这个问题,但我正在尝试使用正则表达式等进行更多练习。
Thanks for helping.谢谢你的帮助。
It could not be done with a single pattern.它无法通过单一模式完成。
Use a pattern chain:使用模式链:
inputString:gsub('.','\0%0%0'):gsub('(.)%z%1','%1'):gsub('%z.(%Z+)',replace)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.