Groovy web console

subscribe to the feed Subscribe
to this

Splitting Strings

Published 1 decade ago by mrhaki with tags string split tokenize
Actions Execute script  ▶ Edit in console Back to console Show/hide line numbers View recent scripts
def s = '''\

assert s.split() instanceof String[]
assert ['username;language,like', 'mrhaki,Groovy;yes'] == s.split()  // Default split on whitespace.
assert ['username', 'language', 'like', 'mrhaki', 'Groovy', 'yes'] == s.split(/(;|,|\n)/)  // Split argument is a regular expression.

def result = []
s.splitEachLine(",") {
    result << it  // it is list with result of split on ,
assert ['username;language', 'like'] == result[0]
assert ['mrhaki', 'Groovy;yes'] == result[1]

assert s.tokenize() instanceof List
assert ['username;language,like', 'mrhaki,Groovy;yes'] == s.tokenize()  // Default tokenize on whitespace.
assert ['username', 'language', 'like', 'mrhaki', 'Groovy', 'yes'] == s.tokenize("\n;,")  // Argument is a String with all tokens we want to tokenize on.