【问题标题】:RegEx for digits, three different conditions数字的正则表达式,三种不同的条件
【发布时间】:2014-04-02 12:30:47
【问题描述】:

问题:我想在 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 检查上述条件吗? 谢谢。

【问题讨论】:

    标签: regex groovy jenkins post-build-event


    【解决方案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"
        }
    }
    

    【讨论】:

    • 我在想,我们可以将第三种情况视为默认情况吗? $RESULT 将始终是仅包含数字的字符串,并且长度永远不会为零...
    • 你可以这样做,但有时最好尽快失败,以防出现问题。与其将错误推送到可能不会被注意到的管道中,不如在这里失败?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    相关资源
    最近更新 更多