Groovy Matcher 对象怎么用?

文章导读
Previous Quiz Next 当我们使用 =~ 操作符匹配正则表达式并找到匹配时,它会返回 Matcher 对象。
📋 目录
  1. A 语法
  2. B 示例 - 搜索所有匹配
  3. C 示例 - 替换所有匹配
A A

Groovy - Matcher 对象



Previous
Quiz
Next

当我们使用 =~ 操作符匹配正则表达式并找到匹配时,它会返回 Matcher 对象。

语法

def regexDigits = "\\d+"
def text = "12243"

def matcher = text =~ regexDigits

matcher 对象提供了多个有用的方法来处理匹配的字符串。

  • find() − find() 方法用于在字符串中搜索下一个匹配。如果找到匹配,则返回 true,否则返回 false。

  • group() 或 [0] − 它返回匹配的子字符串。

  • group(n) 或 [n] − 用于获取第 nth 捕获组的匹配子字符串。

  • start() − start() 方法给出匹配字符串的起始索引。

  • end() − end() 方法返回匹配字符串的结束索引。

  • replaceAll(replacement) − 该方法用传入的替换字符串替换所有匹配的模式出现。

  • replaceFirst(replacement) − 该方法用传入的替换字符串替换第一个匹配的模式出现。

示例 - 搜索所有匹配

我们可以使用 matcher.find() 来搜索字符串的所有出现。

Example.groovy

def text = "Order numbers: ORD-12345, ORD-67890"
def orderRegex = /(ORD-\d+)/

def matcher = text =~ orderRegex

// 查找所有匹配
while (matcher.find()) {
   println "Found order: ${matcher.group(1)} at index ${matcher.start()}"
}

输出

运行上述程序时,我们将得到以下结果。

Found order: ORD-12345 at index 15
Found order: ORD-67890 at index 26

示例 - 替换所有匹配

我们可以使用 matcher.replaceAll() 来搜索并替换字符串的所有出现。

Example.groovy

def text = "Order numbers: ORD-12345, ORD-67890"
def orderRegex = /ORD/

def matcher = text =~ orderRegex

def replacedText = text.replaceAll(orderRegex, 'ORDER-ID')
println "Updated text: ${replacedText}"

输出

运行上述程序时,我们将得到以下结果。

Updated text: Order numbers: ORDER-ID-12345, ORDER-ID-67890