RegEx用于数字,三种不同的条件

时间:2014-04-02 12:30:48

标签: regex groovy jenkins post-build-event

问题:我想在groovy中使用RegEx检查以下条件。 此脚本使用Jenkins Groovy postbuild plugin脚本编写。

String pattern is "JOB_EXIT : $RESULT"

要检查的逻辑:

If ( $RESULT contains only zeros ) {
   // do something
} else if ( $RESULT contains only non-zeros ) {
   // do something else
} else if ( $RESULT contains at least one zero and with some non-zeros ) {
   // do something else
}

尝试失败:

def matcherFail = manager.getLogMatcher(".*JOB_EXIT : ([1-9]+)")
def matcherSuccess = manager.getLogMatcher(".*JOB_EXIT : ([0]*)")

if(matcherFail?.matches()) {
   // do something
} else if(matcherSuccess?.matches()) {
   // do something else
} else if(No idea about this one) {
   // do something else
}

任何人都可以建议RegEx检查以上条件? 谢谢。

1 个答案:

答案 0 :(得分:1)

您也可以使用开关(显示正则表达式模式)

// Some test data
def tests = [ [ input:'JOB_EXIT : 0000', expected:'ZEROS' ],
              [ input:'JOB_EXIT : 1111', expected:'NON-ZEROS' ],
              [ input:'JOB_EXIT : 0010', expected:'MIX' ] ]

// Check each item in test data
tests.each { test ->

    // based on the test input
    switch( test.input ) {
        case ~/JOB_EXIT : (0+)/ :
            println "$test.input is all ZEROS"
            assert test.expected == 'ZEROS'
            break

        case ~/JOB_EXIT : ([^0]+)/ :
            println "$test.input is all NON-ZEROS"
            assert test.expected == 'NON-ZEROS'
            break

        case ~/JOB_EXIT : ([0-9]+)/ :
            println "$test.input is a MIX"
            assert test.expected == 'MIX'
            break

        default :
            println "No idea for $test.input"
    }
}