zoukankan      html  css  js  c++  java
  • Groovy正则表达式复杂逻辑判断实例

    下面的两个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


    ===

  • 相关阅读:
    软件的概念
    打开别人Android项目的方法
    软件工程
    数据预处理技术
    机器学习之监督学习
    C语言指针与二维数组
    徐涛政治押题
    求二叉树的宽度
    解决在某些IE浏览器下字符乱码的问题
    mac系统不能使用127.0.0.2的解决方案
  • 原文地址:https://www.cnblogs.com/darkmatter/p/3606832.html
Copyright © 2011-2022 走看看