前言
- 本篇来学习Groovy正则表达式
正则表达式
- 正则表达式是用于在文本中查找子字符串的模式。 Groovy 使用~ 来支持表达式。Groovy也支持“=~”(创建一个Matcher)和 “==~” (返回boolean,是否给定的字符串匹配这个pattern)操作符
- 当定义正则表达式时,可以使用以下特殊字符
- 有两个特殊的位置字符用于表示一行的开始和结束:caret(∧)和美元符号($)。
- 正则表达式也可以包括量词。加号(+)表示一次或多次,应用于表达式的前一个元素。星号(*)用于表示零个或多个出现。问号(?)表示零或一次。
- 元字符{和}用于匹配前一个字符的特定数量的实例。
- 在正则表达式中,句点符号(。)可以表示任何字符。这被描述为通配符。
- 正则表达式可以包括字符类。一组字符可以作为简单的字符序列,包含在元字符[和]中,如[aeiou]中。对于字母或数字范围,可以使用[a-z]或[a-mA-M]中的短划线分隔符。字符类的补码由方括号内的前导插入符号表示,如[∧a-z]中所示,并表示除指定的字符以外的所有字符。
语法示例
'Groovy' =~ 'Groovy' 'Groovy' =~ 'oo' 'Groovy' ==~ 'Groovy' 'Groovy' ==~ 'oo' 'Groovy' =~ '^G' 'Groovy' =~ 'G$' 'Groovy' =~ 'Gro*vy' 'Groovy' =~ 'Gro{2}vy'
实际例子
// ~ 和= 之间有一个空格, 因为Groovy中存在=~ 操作符号 def reg1 = ~'he*llo' def reg2 = /he*llo/ println "reg1 type is ${reg1.class}" // Pattern类型 println "reg2 type is ${reg2.class}" // String类型 println "hello".matches(reg1) println "hello".matches(reg2)
def val1 = "hello" =~ "he*llo" println val1.class // Matcher 对象 println val1.matches() // true // 简写 def val2 = "hello" ==~ "he*llo" println val2.class // Boolean println val2 // true
- 如果在构建正则表达式字符串的时候, 使用双引号表示字符串,就需要使用\ 来表示单斜线,比如:
def reg3 = "hello \\w*" def reg4 = /hello \w*/ println "hello world" ==~ reg3 println "hello world" ==~ reg4
def reg6 = ~/h(el)(lo)/ def str6 = 'hello world hello nihao' def matcher6 = str6=~reg6 println "first matched substring" println matcher6[0] println matcher6[0][0] println matcher6[0][1] println matcher6[0][2] println matcher6.group(0) println matcher6.group(1) println matcher6.group(2)
def reg8 = /el/ def str8 = "hello world hello" def matcher8 = str8=~reg8 while(matcher8.find()){ println matcher8.group() } matcher8.reset() println "reset the matcher" while(matcher8.find()){ println matcher8.group() }
def compile = ~'^Gro{2}vy' def branch = 'Groovy' def res = "${branch}" ==~ compile println("${res}") if (res){ println('结果为true') }else { println('结果为false') }