该笔记将记录:在 Groovy 中,常用正则表达式,以及常见问题处理。
解决方案
使用 ~string 即可定义 java.util.regex.Pattern 对象。例如 ~"[Gg]roovy" 或者 ~/[Gg]roovy/ 格式
使用 =~ 即可定义 java.util.regex.Matcher 对象
// java.util.regex.Pattern def pattern = ~/\S+er\b/ // java.util.regex.Matcher def matcher = "My code is groovier and better when I use Groovy there" =~ pattern assert matcher instanceof java.util.regex.Matcher // 或者 def matcher = "My code is groovier and better when I use Groovy there" =~ /\S+er\b/ assert matcher instanceof java.util.regex.Matcher
判断字符串是否匹配正则表达式
使用 ==~ 操作符:
assert "2009" ==~ /\d+/ String regex = /^somedata(:somedata)*$/ assert "somedata" ==~ regex // 注意事项: // 如果是多行字符串,应该用 =~ 判断,而 ==~ 会返回 false
判断是否包含某个字符串
使用 =~ 操作符(Matcher):
if ("My code is groovier and better when I use Groovy there" =~ /\S+er\b/) { println "At least one element matches the pattern..." }
使用 ==~ 操作符(Boolean):
if ("My code is groovier and better when I use Groovy there" ==~ /\S+er\b/) { println "At least one element matches the pattern..." }
示例的两种方式是不同的:
1)前者,在 if 语句中的是 Matcher 对象,只检查字符串是否包含与 Matcher 对象匹配的内容
2)后者,在 if 语句中的是 Boolean 对象,可类比于调用 matcher.matches() 方法,进行严格匹配
注意事项:
1)符号两侧是不能交换的,左侧为字符串,右侧为正则表达式;
2)如果 多行字符串 的匹配,需要使用 =~ 符号,而 ==~ 会失败;
找到所有匹配元素
找到所有匹配元素,并返回匹配元素的列表:
def text = """ This text contains some numbers like 1024 or 256. Some of them are odd (like 3) or even (like 2). """ def result = (text =~ /\d+/).findAll() assert result == ["1024", "256", "3", "2"]
获取特定匹配的内容(using named group)
def matcher = "JIRA-231 lorem ipsum dolor sit amet" =~ /^(?<jira>[A-Z]{2,4}-\d{1,3}).*$/ matcher.matches() // 必须执行该方法,才能从 group() 中取值 assert matcher.group("jira") == "JIRA-231" assert matcher.replaceAll('Found ${jira} ID') == 'Found JIRA-231 ID'
参考文献
Groovy Regular Expressions – The Definitive Guide
Groovy Regular Expressions – The Definitive Guide (Part 1)
Regex in Groovy to accept multiple lines – Stack Overflow