Groovy Goodness: Getting Parts Of A String Enclosed By Strings
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 takeBefore
and 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 takeBefore
, takeAfter
and takeBetween
methods with different arguments:
def text = 'Just saying: "Groovy is gr8!"'
// Return all characters before the first quote.
assert text.takeBefore('"') == 'Just saying: '
// Return everything after the colon.
assert text.takeAfter(': ') == '"Groovy is gr8!"'
// Return everything between two quotes.
assert text.takeBetween('"') == 'Groovy is gr8!'
// Return text between is and !.
assert text.takeBetween('is', '!') == ' gr8'
// When no value can be found
// an empty string is returned.
assert text.takeBefore('?') == ''
assert text.takeAfter('Java') == ''
assert text.takeBetween('-') == ''
assert text.takeBetween('[', '/') == ''
def sample = 'JVM languages are "Groovy", "Clojure", "Java".'
assert sample.takeBetween('"') == 'Groovy'
// We can also specify which occurrence we
// want for a text between same strings.
assert sample.takeBetween('"', 0) == 'Groovy'
assert sample.takeBetween('"', 1) == 'Clojure'
assert sample.takeBetween('"', 2) == 'Java'
def users = "Users: [mrhaki], [hubert]"
assert users.takeBetween('[', ']') == 'mrhaki'
// We can also specify which occurrence we
// want for a text between to strings.
assert users.takeBetween('[', ']', 0) == 'mrhaki'
assert users.takeBetween('[', ']', 1) == 'hubert'
// When no occurrence an empty string is returned.
assert users.takeBetween('[', ']', 2) == ''
Written with Groovy 3.0.2.