Lua模式匹配,重复字符 [英] Lua pattern matching, repeating character

查看:499
本文介绍了Lua模式匹配,重复字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是模式匹配的初学者.我了解到Lua的模式匹配与标准有点不同,所以我一直无法找到一种方法来将正则表达式解决方案用于此问题以适应Lua代码.

我正在尝试替换字符串中重复字符的最长子字符串.

例如,在abbbccccc中,它将找到一个bbb ccccc.

这不起作用,它只匹配整个字符串:

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.

感谢您的帮助.

推荐答案

inputString:gsub('.','\0%0%0'):gsub('(.)%z%1','%1'):gsub('%z.([^%z]+)',replace)

这篇关于Lua模式匹配,重复字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆