Groovy 3 adds the
takeBetween method to the
String class. With this method we can get all the characters that are enclosed by string values. We can specify one enclosed string value and then all text between the the first occurrence of the string and the second occurrence is returned. If multiple parts are enclosed by the string values we can also specify which occurrence we want. If the text is enclosed by different string values we can use a variant of
takeBetween that takes two string values to indicate the boundaries of the text we want. Also with two different enclosed string values we can use an argument to get the n-th occurrence of the string that is found.
Since Groovy 3 we can also use
takeAfter to get the string before or after a given string value. All three methods will return an empty string if no text can be found.
In the following example we use the
takeBetween methods with different arguments: