Lua模式匹配,重复字符

3

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.

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.

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.

1个回答

1
无法使用单个模式完成。
使用模式链:
inputString:gsub('.','\0%0%0'):gsub('(.)%z%1','%1'):gsub('%z.(%Z+)',replace)

我本来希望只需要一个gsub函数调用就可以了,但我想这样也行。 - flameiguana
@flameiguana - 似乎不可能使用单个模式完成此任务。 - Egor Skriptunoff
“%Z = [^%z]” 不是吗? - André Levy
1
@AndréLevy - 谢谢。已改进。 - Egor Skriptunoff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接