Groovy正则表达式复杂逻辑判断实例

本文通过示例展示了Groovy中正则表达式的使用方法,包括如何进行跨行匹配以及利用闭包处理匹配结果。示例代码比较了两种不同的正则模式,并对四条消息进行了匹配测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面的两个pattern(p1和p2)分别代表了(A or B) and (C or D)和(A and B) or (C and D)的跨行匹配结果,当然还可以用正则表达式构建更复杂的pattern,但这个实例证明了Groovy具备跨行匹配复杂逻辑表达式的能力。

值得注意的是,多行匹配文本时需要在匹配字符串前加“(?ms)”。

该实例同时演示了Groovy闭包的使用方法。 源代码

msg1 = '''one two three four

five six'''

msg2 = '''Jan Feb Mar

Apr May Jun'''

msg3 = '''one two three

Apr May Jun'''

msg4 = '''Jan Feb Mar

four five six'''

p1 = / (?ms) (two|Feb).*(five|May)/

p2 = / (?ms) (two.five)|(Feb.May)/

msgs = [msg1, msg2, msg3, msg4]

patterns = [p1, p2]

patterns.each { pattern->

println 'pattern is: '+pattern

msgs.each { msg->

println 'msg is: '+msg

println 'match result is:'

matcher = msg =~ pattern

if (matcher)

println "true"

else

println "false"

println '---'

}

println '==='

} 运行结果 pattern is: (?ms)(two|Feb).*(five|May)

msg is: one two three four

five six

match result is:

true


msg is: Jan Feb Mar

Apr May Jun

match result is:

true


msg is: one two three

Apr May Jun

match result is:

true


msg is: Jan Feb Mar

four five six

match result is:

true


===

pattern is: (?ms)(two.five)|(Feb.May)

msg is: one two three four

five six

match result is:

true


msg is: Jan Feb Mar

Apr May Jun

match result is:

true


msg is: one two three

Apr May Jun

match result is:

false


msg is: Jan Feb Mar

four five six

match result is:

false


===

转载于:https://www.cnblogs.com/darkmatter/p/3606832.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值