参考文献地址:http://docs.groovy-lang.org/docs/groovy-2.5.8/html/documentation/#_regular_expression_operators
1.创建正则表达式对象
使用 ~ 符号创建java.util.regex.Pattern对象
def p = ~/foo/
p= ~'foo'
p= ~"foo"
println p instanceof Pattern /*Output true */
2.使用GString来重用Pattern对象
import java.util.regex.Pattern import java.util.regex.Matcher def pattern = ~/foo/ def p = ~"${pattern}" println p instanceof Pattern def matcher = 'foo abc'=~ p if(!matcher){ // 等价于if(!matcher.find()) println 'Not found foo' }else{ println 'Found foo' } /*Output true Found foo */
3.Match Operator:全字匹配操作符 ==~
import java.util.regex.Pattern import java.util.regex.Matcher def pattern = ~/foo/ def p = ~"${pattern}" println p instanceof Pattern def matcher = 'foo abc'==~ p if(!matcher){ println 'Not found foo' }else{ println 'Found foo' } /*Output true Not found foo */