Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua pattern matching, repeating character

Tags:

regex

lua

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.

like image 551
flameiguana Avatar asked Jul 30 '26 00:07

flameiguana


1 Answers

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)
like image 185
Egor Skriptunoff Avatar answered Jul 31 '26 23:07

Egor Skriptunoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!