Library contents

Groovy tokenize and split

Groovy tokenize skips empty tokens. Java String.split with a negative limit preserves both interior and trailing empty fields.

A simple example

tokenize and split

  1. Start with a,b
  2. Do this Split at the comma
  3. Result a and b
The comma separates two nonempty fields.

Syntax

Groovy syntax
line.tokenize(',') / line.split(',', -1)
Run this example in Groovy

Save the program as Lesson.groovy. Use Groovy 4 on the JVM.

groovy Lesson.groovy

Choose how to handle empty columns

An import can contain a blank record, an empty field or a missing field. Check how the reader represents each case so a user's deliberate blank is not mistaken for the end of the data.

First output line[A, B]
Lesson.groovy
def line = 'A,,B,'
println line.tokenize(',')
def columns = line.split(',', -1)
println columns.size()
println '[' + columns.last() + ']'
Output
[A, B]
4
[]

The two approaches answer different questions. Counting present labels yields two, while inspecting all positions in a four-column record yields four.

Groovy documentation for tokenize and split

Advertisements

Count a choir equipment list

A teacher receives one comma-separated line of items. Split the record at each comma. Each field is nonempty, so the station can count the resulting entries directly.

Givenmic,stand,cable
Worked result3

Count a solo order

The stationery desk receives one item without a separator. Split the record at each comma. Each field is nonempty, so the station can count the resulting entries directly.

Givenpaper
Worked result1