lua正则匹配中文_Lua正则表达式匹配

本文介绍了Lua中的正则表达式,包括pattern、string.find、string.match、string.gmatch和string.gsub等函数的用法。通过实例解析了各函数的功能,如查找、匹配、全局匹配和替换,并探讨了Lua正则中的魔法字符及其作用。
摘要由CSDN通过智能技术生成

最近学习了一下lua的正则表达式,在此记录一下。

为应对复杂多变的字符串匹配需求,很多语言都有对正则表达式的支持。Lua因为要保持简洁与小巧的设计目标,并没有像perl和python一样支持全部posix标准正则表达式规则。比如没有{n}匹配n次的规则,字符{和}都只是作为普通字符存在,字符|在posix标准正则表达式中表示或关系,在lua的pattern中也只是作为普通字符。

在lua中,一个正则表达式被称作为pattern,pattern中一对圆括号()包含的区域被称作为capture.

lua中一共有4个系统函数支持正则表达式参数,分别为string.find,string.match,string.gmatch,string.gsub。

lua正则表达式应用的系统函数

string.find

函数的带参形式为string.find (s, pattern [, init [, plain]])。函数有2个必要参数s和pattern,对应源字符串和相应的正则表达式,还有2个可选参数,init表示起始匹配位置,plain表示是否将pattern中的魔法字符无效化。

函数基本目标为,找到第一个匹配的位置。

来看官方文档对此函数的说明:

Looks for the first match of pattern in the string s. If it finds a match, then find returns the indices of s where this occurrence starts and ends; otherwise, it returns nil. A third, optional numeric argument init specifies where to start the search; its default value is 1 and can be negative. A value of true as a fourth, optional argument plain turns off the pattern matching facilities, so the function does a plain "find substring" operation, with no characters in pattern being considered magic. Note that if plain is given, then init must be given as well.If the pattern has captures, then in a successful match the captured values are also returned, after the two indices.

函数返回匹配的第一个字符串起始位置和结尾位置,如果有capture存在,则在之后返回capture匹配的值。

下面的代码演示了没有capture存在和有capture存在时的函数返回结果:

print(string.find('hello world','hello')) --> 1 5

print(string.find('hello world','(%a+)')) --> 1 5 hello

对于可选参数init和plain,以下代码作了示例:

print(string.find('hello (%a+) world','(%a+)',1,true)) --> 7 11

init = 1表示从第一个字符'h'开始搜索,plain = true表示pattern中的魔法字符全部无效化,以普通字符处理,因此匹配的字符从第7个字符'('开始,第11个字符')'结束。

stri

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值