下面的兩個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
===