npst npst - 1 month ago 6
Groovy Question

Getting a substring from a list of strings

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?

Answer

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]
  }
}
Comments