「Groovy」- 正则表达式 @20210409

问题描述

该笔记将记录:在 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

判断是否包含某个字符串

使用 =~ 操作符(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)符号两侧是不能交换的,左侧为字符串,右侧为正则表达式

找到所有匹配元素

找到所有匹配元素,并返回匹配元素的列表:

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」- 常用字符串操作(String)
「Groovy」- 常用 MAP 操作
「Groovy」- 常用列表操作(List)
「Groovy」- 循环(学习笔记)

参考文献

Groovy Regular Expressions - The Definitive Guide
Groovy Regular Expressions - The Definitive Guide (Part 1)


posted @ 2021-04-09 18:10  研究林纳斯写的  阅读(156)  评论(0编辑  收藏  举报