首页 > 其他 > 详细

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

时间:2021-01-27 09:59:23      阅读:89      评论:0      收藏:0      [点我收藏+]

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

最常用匹配

rexMatchp

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

rex 组合函数

1. rexCompile

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

2. rexExecute

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

3. rexSubstitute

  • rexSubstitute("outputType")
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 组合函数

  • 相比 rex 更加灵活,pattern 中能接近 Perl 的便捷,例如上面的例子中可以少写一些转义符。
  • 演示一下利用 pcreMatchppcreSubstitute 这两个函数完成上面的匹配效果。
pcreMatchp("^(SHORT).+(net[0-9]+).+(net[0-9]+).+" "SHORT 1. net01 - net02 in BLOCK")
; => t
pcreSubstitute("\\1 -> \\2 -> \\3")
; => "SHORT -> net01 -> net02"

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

原文:https://www.cnblogs.com/yeungchie/p/14333186.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!