I’m just starting with Groovy. I’m sure that I’m missing something stupid. Can someone tell me why this code fails in the groovy console? It thinks that there are only 14 words and 1 line in the input string.
def input = """
line1: 50 65 42
line2: 123 456 352 753 1825
line3: 10 25 20 48 107
"""
words = input.split(/ /)
lines = input.split(/^/)
assert words.size() == 16
assert lines.size() == 3
In the case of the first
assert, the error message can hint to where the problem is at:There are some commas missing there and the way the
wordsvalue is printed seems wrong. What is happening is thatinput.split(/ /)is splitting the input string by spaces, but, as it also contains newlines, some words are not split, e.g.,'42\nline2:'.To see this more clearly, we can use the
inspectmethod, which gives us a string with the literal form of an object:To split a word by whitespace Groovy adds a convenience non-parametrized
splitmethod:And to get the lines of a string you can use
readLines.Notice, however that
readLineswill return four elements, as there is a first empty line (i don’t know why it ignores the last empty line though), so theassert lines.size() == 3will still fail.You can filter-out those empty lines using
Collection#findAll()on the resulting list, or callingString#findAll(Pattern)directly on the input string: