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

bir*_*rdy 12 regex groovy

如果我有一个像这样的字符串:

s = "This is a simple string 234 something else here as well 4334
Run Code Online (Sandbox Code Playgroud)

和一个正则表达式:

regex = ~"[0-9]{3}"
Run Code Online (Sandbox Code Playgroud)

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

tim*_*tes 22

你可以使用CharSequence.findAll:

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

assert triads == ['234', '433']
Run Code Online (Sandbox Code Playgroud)

最新文件 CharSequence.findAll

  • 没有区别....这是完全相同的调用,只是使用不同的字符串分隔字符 (3认同)
  • 应该是`s.findAll(/[0-9]{3}/)` (2认同)

Fed*_*zza 11

您必须使用捕获组.你可以查看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!")
}
Run Code Online (Sandbox Code Playgroud)

作为旁注:

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.
Run Code Online (Sandbox Code Playgroud)

  • `matcher.matches()`旨在用于匹配完整的字符串,使用不同的语法.我只是使用`if(matcher.getCount> 0)`来检查匹配. (6认同)

hwn*_*wnd 8

你可以这样做.

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' }
Run Code Online (Sandbox Code Playgroud)

输出(工作演示)

234
433
Run Code Online (Sandbox Code Playgroud)