[ Skill ] 正则表达式 几种常用的使用方法

https://www.cnblogs.com/yeungchie/

最常用匹配

rexMatchp

  • rexMatchp(t_pattern t_targetString)
rexMatchp("^SHORT.+" "SHORT 1. net01 - net02 in BLOCK")    ; 匹配以 SHORT 开头(^),后接任意字符(.)一次或多次(+)的字符串。
; => t
rexMatchp("^CONNECT.+" "SHORT 1. net01 - net02 in BLOCK")
; => nil

rex 组合函数

1. rexCompile

  • rexCompile(t_pattern)
rexCompile("^SHORT.+")    ; 定义 pattern ( 模式 / 匹配关键字 ) 。
; => t

2. rexExecute

  • rexExecute(t_targetString)
rexExecute("SHORT 1. net01 - net02 in BLOCK")    ; 定义目标字符串 ( 被匹配 ) 。
; => t

3. rexSubstitute

  • rexSubstitute(t_outputGroup)
rexSubstitute("&")    ; & 用来表示 pattern 匹配到的字符串。
; => "SHORT 1. net01 - net02 in BLOCK"

4. 分组匹配

  • 使用关键符号 "\\(pattern\\)" 来对 pattern 中的子 pattern 进行分组。
rexCompile("^\\(SHORT\\).+\\(net[0-9]+\\).+\\(net[0-9]+\\).+")    ; 3 个分组。
; => t
rexExecute("SHORT 1. net01 - net02 in BLOCK")
; => t
rexSubstitute("\\0")    ; \\0 与上面的 & 相同。
; => "SHORT 1. net01 - net02 in BLOCK"
rexSubstitute("\\1 -> \\2 -> \\3")    ; \\ 接数字用来表示第几个分组。
; => "SHORT -> net01 -> net02"

Tips 🍉 rexCompile + rexExecute 不是必须的,直接使用 rexMatchp + rexSubstitute 也可以。

pcre 组合函数

  • PCRE (Perl Compatible Regular Expressions),是一个 Perl 库,包括 perl 兼容的正则表达式库。
  • 相比使用 rex 更加灵活,且速度更快,pattern 中能接近 Perl 的便捷,例如上面的例子中可以少写一些转义符。
  • 演示一下利用 pcreMatchppcreSubstitute 这两个函数完成上面的匹配效果。
pcreMatchp("^(SHORT).+(net\\d+).+(net\\d+).+" "SHORT 1. net01 - net02 in BLOCK")
; => t
pcreSubstitute("\\1 -> \\2 -> \\3")
; => "SHORT -> net01 -> net02"

pcreListCompileOptBits

caseLess        (0x00000001) - Do caseless matching
multiLine       (0x00000002) - ^ and $ match newlines within data
dotAll          (0x00000004) - . matches anything, including NL
extended        (0x00000008) - Ignore whitespace and # comments
anchored        (0x00000010) - Force pattern anchoring
dollar_endonly  (0x00000020) - $ not to match newline at end
ungreedy        (0x00000200) - Invert greediness of quantifiers
no_auto_capture (0x00001000) - Disable numbered capturing parentheses (named ones available)
firstline       (0x00040000) - Force matching to be before newline

pcreListExecOptBits

+ anchored        (0x00000010) - Force pattern anchoring
+ notbol          (0x00000080) - Subject is not the beginning of a line
+ noteol          (0x00000100) - Subject is not the end of a line
+ notempty        (0x00000400) - An empty string is not a valid match
+ partial         (0x00008000) - Return error for a partial match
posted @ 2021-01-27 01:42  YEUNGCHIE  阅读(2265)  评论(0编辑  收藏  举报