實例代碼:獲取 [] 里面的內容
Lua版本
print('-----------------') for s in string.gmatch('pp[1g1]ppp[1jj2]pp[1413]ppp', '%[(%w+)%]') do print(s) end print('-----------------')
C#版本
string str=@"[11][12][1413]"; foreach(Match m in Regex.Matches(str,@"\[(\w+)\]")) { print(m.Groups[1].Value); }
下面的表列出了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
單個字符(除^$()%.[]*+-?外): 與該字符自身配對
.(點): 與任何字符配對
%a: 與任何字母配對
%c: 與任何控制符配對(例如\n)
%d: 與任何數字配對
%l: 與任何小寫字母配對
%p: 與任何標點(punctuation)配對
%s: 與空白字符配對
%u: 與任何大寫字母配對
%w: 與任何字母/數字配對
%x: 與任何十六進制數配對
%z: 與任何代表0的字符配對
%x(此處x是非字母非數字字符): 與字符x配對. 主要用來處理表達式中有功能的字符(^$()%.[]*+-?)的配對問題, 例如%%與%配對
[數個字符類]: 與任何[]中包含的字符類配對. 例如[%w_]與任何字母/數字, 或下划線符號(_)配對
當上述的字符類用大寫書寫時, 表示與非此字符類的任何字符配對. 例如, %S表示與任何非空白字符配對.例如,’%A’非字母的字符
‘%’ 用作特殊字符的轉義字符,因此 ‘%.’ 匹配點;’%%’ 匹配字符 ‘%’。轉義字符 ‘%’不僅可以用來轉義特殊字符,還可以用於所有的非字母的字符。當對一個字符有疑問的時候,為安全起見請使用轉義字符轉義他。
+ 匹配前一字符1次或多次
* 匹配前一字符0次或多次
- 匹配前一字符0次或多次
? 匹配前一字符0次或1次
【更多參考】
Lua的字符串匹配與正則表達式
https://www.cnblogs.com/meamin9/p/4502461.html
正則表達式中文手冊
https://github.com/ziishaned/learn-regex/blob/master/translations/README-cn.md
在線測試工具
https://regex101.com/
相關視頻
https://www.bilibili.com/video/BV1da4y1p7iZ?from=search&seid=1887659927205983862