lua的模式匹配

模式:

  • 字符类:(character classes)
. all characters
%a letters
%c control characters
%d digits
%l lower -case letters
%p punctuation characters
%s space characters
%u upper-case letters
%w alphanumeric characters
%x hexadecimal digits
%z the character whose representation is 0
  • 他们的大写版本是他本身的互补。

魔法字符:

( ) . % + - * ? [ ] ^ $
  • 用%进行转义。'%%'代表'%'

字符集(char -set ):使用字符集可以自定义字符类。

1.不同的字符类,和单字符之间用[]
[%w_]匹配字母数字字符和下划线。
[01]匹配二进制数
2.要想字符集内包含字符区间,起止之间加上-
[0-9] 相当于 %d
[0-9a-fA-F]相当于 %x
3.如果想得到该字符集的互补,前面加上^
[^0-7] 任何非八进制数字

重复或可选修饰符

+ 1 or more repetitions,匹配最长的,
* 0 or more repetitions  最长的
- also 0 or more repetitions 最短的
? optional (0 or 1 occurrence) 

捕获

捕获机制允许一个模式串中的一部分来匹配目标串种的一部分。写法是模式串中你需要捕获的那部分用()括起来,例如:
我们也可以将捕获用于模式串自身,"(["'])(.-)%1",这里的%1表示匹配第一个捕获的一份拷贝。

local host = 'wyc.com'
local aa,bb = host:match("([^%.]+)%.([^%.]+)")

-- aa:wyc
-- bb:  com

lua的string库

string.find将查找目标模板在给定字符串中出现的位置,找到返回起始和结束位置,没找到返回nil。
string.match()返回匹配到的字符。
string.gmatch函数将返回一个迭代器,用于迭代所有出现在给定字符串中的匹配字符串。
string.gsub的参数可以是string,其实,也可以是个函数,或是table,如果是函数,就会用捕获的内容作为参数调用该函数,将返回的内容作为替换字符串。如果是table,则用捕获的内容为key去取table的值来作为替换字符串,如果不存在,就不做替换。

c参考于这个 http://blog.csdn.net/booirror/article/details/39831869

原文地址:https://www.cnblogs.com/mentalidade/p/7061299.html