在groovy

时间:2016-02-20 21:01:15

标签: regex groovy

我不明白我应该如何使用groovy中的正则表达式,尽管它有多个运算符可以使用它。

import java.util.regex.*

def line = "Line with 1 digits"

Pattern p = Pattern.compile("\\d+")
Matcher m = p.matcher(line)
if (m.find()) { // true
    println "found digit"
} else {
    println "not found digit"
}

if (line ==~ /\\d+/) { // false
    println "found"
} else {
    println "not found"
}

if (line =~ /\\d+/) { // false
    println "found"
} else {
    println "not found"
}

java代码的示例中,它发现字符串中有一个数字成功。但是在groovy中却无法做到。

有什么问题?

2 个答案:

答案 0 :(得分:3)

请参阅此slashy string reference

  

Slashy字符串对于定义正则表达式和模式特别有用,因为不需要转义反斜杠。

你需要在\d Groovy slashy字符串中使用/\d+/的单个反斜杠来定义正则表达式。

if (line =~ /\d+/) { // false
    println "found"
} else {
    println "not found"
}

line =~ /\d+/检查line 是否包含一个或多个数字。

line2 ==~ /\d+/检查整个字符串是否只包含数字。

请参阅IDEONE demo

另请参阅一些more information about using regex in Groovy at regular-expressions.info

答案 1 :(得分:0)

您可以使用find

if (line.find(/\d+/)) {
    println "found"
} else {
    println "not found"
}