如何使用正则表达式查找字符串中模式的所有匹配项

时间:2014-08-28 21:07:15

标签: regex groovy

如果我有一个字符串:

s = "This is a simple string 234 something else here as well 4334

和正则表达式如:

regex = ~"[0-9]{3}"

如何使用该正则表达式从字符串中提取所有单词?在这种情况下234433

3 个答案:

答案 0 :(得分:19)

您可以使用CharSequence.findAll

def triads = s.findAll("[0-9]{3}")

assert triads == ['234', '433']

Latest documentation of CharSequence.findAll

答案 1 :(得分:9)

您必须使用捕获组。您可以查看有关它的groovy文档:

http://mrhaki.blogspot.com/2009/09/groovy-goodness-matchers-for-regular.html

例如,您可以使用以下代码:

s = "This is a simple string 234 something else here as well 4334"
regex = /([0-9]{3})/

matcher = ( s=~ regex )

if (matcher.matches()) {
    println(matcher.getCount()+ " occurrence of the regular expression was found in the string.");
    println(matcher[0][1] + " found!")
}

作为旁注:

m[0] is the first match object.
m[0][0] is everything that matched in this match.
m[0][1] is the first capture in this match.
m[0][n] is the n capture in this match.

答案 2 :(得分:5)

你可以这样做。

def s = "This is a simple string 234 something else here as well 4334" 
def m = s =~ /[0-9]{3}/
(0..<m.count).each { print m[it] + '\n' }

输出Working Demo

234
433