如果我有一个像这样的字符串:
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)
如何使用该正则表达式从字符串中提取所有单词?在这种情况下,234
和433
?
tim*_*tes 22
你可以使用CharSequence.findAll
:
def triads = s.findAll("[0-9]{3}")
assert triads == ['234', '433']
Run Code Online (Sandbox Code Playgroud)
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)
你可以这样做.
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)
归档时间: |
|
查看次数: |
28537 次 |
最近记录: |