如何在Groovy中将字符串与模式匹配 [英] How to match String with Pattern in Groovy

查看:112
本文介绍了如何在Groovy中将字符串与模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图确定一个简单的正则表达式是否与Groovy中的字符串匹配。这是我在Gradle中的任务。我试图用我在网上找到的两种不同的方式进行匹配,但它们都不起作用。它总是打印出NO ERROR FOUND。

 任务aaa<< {
String stdoutStr =找到bla bla错误:\\\
hehe立即中止\\\
hehe
println stdoutStr
Pattern errorPattern =〜/ error /
// if(errorPattern .matcher(stdoutStr).matches()){
if(stdoutStr.matches(errorPattern)){
println发现错误
抛出新的GradleException(Error in propel:+ stdoutStr )
} else {
printlnNO ERROR FOUND
}
}


(?s)忽略。*的换行符(DOTALL)和正则表达式意味着完全匹配。所以以 ==〜作为快捷方式:

  if(bla bla错误发现:\\\
hehe现在放弃\\\
hehe==〜/(?s).*errors.*/)...


I am trying to decide whether a simple regular expression matches a string in Groovy. Here's my task in gradle. I tried to match with 2 different ways I found on the net, but neither of them works. It always prints out "NO ERROR FOUND"

task aaa << {
    String stdoutStr = "bla bla errors found:\nhehe Aborting now\n hehe"
    println stdoutStr
    Pattern errorPattern = ~/error/
//  if (errorPattern.matcher(stdoutStr).matches()) {
    if (stdoutStr.matches(errorPattern)) {
        println "ERROR FOUND"
        throw new GradleException("Error in propel: " + stdoutStr)
    } else {
        println "NO ERROR FOUND"
    }
}

解决方案

(?s) ignores line breaks for .* (DOTALL) and the regexp there means a full match. so with ==~ as shortcut it's:

if ("bla bla errors found:\nhehe Aborting now\n hehe" ==~ /(?s).*errors.*/) ...

这篇关于如何在Groovy中将字符串与模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆