Groovy - 正则表达式
正则表达式是一种用于在文本中查找子字符串的模式。Groovy 原生支持正则表达式,使用 ~regex 表达式。引号内包围的文本表示用于比较的表达式。
例如,我们可以按以下方式创建一个正则表达式对象 −
def regex = ~'Groovy'
当 Groovy 操作符 =~ 用作 if 和 while 语句(参见第 8 章)中的谓词(返回 Boolean 的表达式)时,左侧的 String 操作数将与右侧的正则表达式操作数进行匹配。因此,以下每个示例都会返回 true。
在定义正则表达式时,可以使用以下特殊字符 −
有两个特殊的定位字符,用于表示行首和行尾:插入符 (^) 和美元符号 ($)。
正则表达式还可以包含量词。加号 (+) 表示前一个元素的一遍或多遍。星号 (*) 用于表示零遍或多遍。问号 (?) 表示零遍或一遍。
元字符 { 和 } 用于匹配前一个字符的特定数量实例。
在正则表达式中,句点符号 (.) 可以表示任意字符。这被称为通配符字符。
正则表达式可以包含字符类。一组字符可以作为封闭在元字符 [ 和 ] 中的简单字符序列给出,例如 [aeiou]。对于字母或数字范围,可以使用连字符分隔符,例如 [a-z] 或 [a-mA-M]。字符类的补集用方括号内的前导插入符表示,例如 [^a-z],表示除指定字符外的所有字符。以下给出了一些正则表达式的示例
示例 - 使用 find (=~) 操作符
find 操作符检查给定的正则表达式是否匹配字符串的任何部分。如果找到匹配,则返回 true,否则返回 false。
Example.groovy
def text = "Groovy is a powerful and rich programming language"
def regex = "power.*"
def matcher = text =~ regex
if (matcher) {
println "Found a match!"
// print the first match found
println "Matched text: ${matcher[0]}"
} else {
println "No match."
}
输出
运行上述程序时,我们将得到以下结果。
Found a match! Matched text: powerful and rich programming language
示例 - 使用 match (==~) 操作符
match 操作符检查给定的正则表达式是否匹配整个字符串。如果整个字符串匹配正则表达式,则返回 true,否则返回 false。
Example.groovy
def text = "Groovy" def textExactMatch = "Groovy" def textPartialMatch = "Groo" println text ==~ textExactMatch println text ==~ textPartialMatch
输出
运行上述程序时,我们将得到以下结果。
true false