Split a comma-separated string into a list of fields.

← Operators and Expressions · Ref: Q1165

Use the split method with a RegEx parameter:

  fields <- line.split(/,/)

The split() method takes a RegEx and returns a List of String. You can then stream the result with cat or access individual elements. See Q33 for regular expressions. See Q175 for string transform patterns.

Example

#!ek9
defines module qa.operators.splitstring

  defines program

    SplitStringDemo()
      stdout <- Stdout()

      // Split a CSV line by comma
      csvLine <- "Alice,Bob,Charlie,Diana"
      fields <- csvLine.split(/,/)
      stdout.println(`Fields: ${fields}`)

      // Stream the split results
      stdout.println("Individual fields:")
      cat fields > stdout

      // Split with more complex regex (whitespace)
      sentence <- "Hello   World   EK9"
      words <- sentence.split(/ +/)
      stdout.println(`Words: ${words}`)

      // Split and count
      fieldCount <- length fields
      stdout.println(`Number of fields: ${fieldCount}`)

Common mistakes

E50060 — split() takes a RegEx (delimited by '/'), not a String - use /,/ not ",". See ek9 -h E50060 for details.

Incorrect:

      fields <- csvLine.split(",")

Correct:

      fields <- csvLine.split(/,/)
Other ways to ask this
  • Write code to split a CSV line by commas into separate fields
  • I have a comma-delimited string and need each field as a list element
  • Given "Alice,Bob,Charlie", produce a list ["Alice", "Bob", "Charlie"]
  • In Java I'd use str.split(","). Write the EK9 equivalent

Coming from another language?

Java: str.split(",") returns String[]. Python: str.split(",") returns list. Rust: str.split(',').collect(). Go: strings.Split(str, ","). EK9: str.split(/,/) takes RegEx, returns List of String.

Keywords: comma, csv, delimiter, fields, list, parse, regex, split, string