Reputation: 136
So, as part of learning the language, I wanted to check three strings for a certain pattern and return the first match of that pattern only.
My attempt was to use a combination of find and regular expressions to traverse the list:
def date = [
"some string",
"some other string 11.11.2000",
"another one 20.10.1990"
].find { title ->
title =~ /\d{2}\.\d{2}\.\d{4}/
}
This kind of works, leaving the whole string in date
.
My goal, however, would be to end up with "11.11.2000" in date
; I assume somehow I should be able to access the capture group, but how?
Upvotes: 2
Views: 105
Reputation: 50285
Extending UnholySheep's answer, you can also do this:
assert [
"some string",
"some other string 11.11.2000",
"another one 20.10.1990"
].findResult { title ->
def matcher = title =~ /\d{2}\.\d{2}\.\d{4}/
matcher.find() ? matcher.group() : null
} == '11.11.2000'
For all matches, just use findResults
instead of findResult
, like this:
assert [
"some string",
"some other string 11.11.2000",
"another one 20.10.1990"
].findResults { title ->
def matcher = title =~ /\d{2}\.\d{2}\.\d{4}/
matcher.find() ? matcher.group() : null
} == ['11.11.2000', '20.10.1990']
Upvotes: 2
Reputation: 4096
If you want to return a specific value when finding a matching element in a collection (which as in your case might be part of that element), you need to use findResult.
Your code might then look like this
def date = [
"some string",
"some other string 11.11.2000",
"another one 20.10.1990"
].findResult { title ->
def res = title =~ /\d{2}\.\d{2}\.\d{4}/
if (res) {
return res[0]
}
}
Upvotes: 4