最近学习了一下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