The split() function in Groovy is a method on String that divides the string into an array of substrings based on a delimiter, returning a String[] (or a List if you use the tokenize() variant). The simplest usage is "a,b,c".split(','), which returns ["a", "b", "c"]. This article covers the syntax, the key differences from Java’s split, the regex behavior, and common pitfalls.
Background: Groovy’s String Handling
Groovy is a dynamic language for the JVM that extends Java’s String class with many convenience methods. The split() method is inherited from Java’s String class, but Groovy adds its own tokenize() method and also allows you to call split() with a String or a Pattern. In Groovy, you can also use the split() method on a GString (interpolated string) because it gets coerced to a String automatically. The method is part of the standard Groovy JDK (GDK) enhancements, so no extra imports are needed.
Basic Syntax and Examples
The split() method takes one argument: the delimiter, which is interpreted as a regular expression (regex) by default. Here are the basic forms:
"a,b,c".split(',')→ returns["a", "b", "c"]as aString[]."a,b,c".split(/,/)→ same result, using a regex pattern."a1b2c".split(/\d/)→ splits on any digit, returns["a", "b", "c"]."a,b,c".tokenize(',')→ returns aList["a", "b", "c"]and treats the delimiter as a literal string, not a regex.
Note that split() returns an array, so if you want a list, you can do "a,b,c".split(',') as List or use tokenize().
How It Works: Regex vs. Literal Delimiter
The key detail is that split() uses a regular expression. This means special characters like ., |, *, ?, +, (, ), [, ], {, }, ^, $, and \ need to be escaped. For example, to split on a literal period, you must write "a.b.c".split(/\\./) or "a.b.c".split("\\."). If you use tokenize(), the delimiter is treated as a literal string, so "a.b.c".tokenize('.') works directly. Another difference: tokenize() splits on any of the characters in the delimiter string, not the whole string as a single delimiter. For instance, "a-b_c".tokenize('-_') splits on both hyphen and underscore, while split() would need a regex like /[-_]/.
Common Problems and Pitfalls
One frequent issue is trailing empty strings. Java’s split() removes trailing empty strings by default. For example, "a,b,".split(',') returns ["a", "b"], not ["a", "b", ""]. To keep them, you must use the negative limit: "a,b,".split(',', -1) returns ["a", "b", ""]. Another pitfall is that split() with a regex that matches an empty string (like "") can produce unexpected results. Also, splitting on a pipe | without escaping will split on every character because | is an alternation operator in regex. Another common mistake is assuming tokenize() and split() are interchangeable; they are not, as explained above.
Comparison with Java and Other Methods
In Java, String.split() behaves identically to Groovy’s, but Groovy adds tokenize() which is not in Java. Groovy also allows passing a Pattern object directly to split(). For example, def pattern = ~/,/; "a,b".split(pattern) works. Another alternative is using the replaceAll() method combined with split(), but that is rarely needed. For simple comma-separated values, tokenize() is often faster because it does not compile a regex. However, split() is more flexible for complex delimiters. If you need to split a string into individual characters, you can use "abc".toList() or "abc".split('') (though the latter may produce leading/trailing empty strings in some versions).
How to Choose: split() vs. tokenize() vs. regex
Use split() when you need regex power, such as splitting on multiple different delimiters, or when you need to keep trailing empty strings (using the negative limit). Use tokenize() when you have a simple literal delimiter and you want a List result, or when you want to split on any of several characters without writing a regex. For example:
- Split on comma or semicolon:
"a;b,c".split(/[;,] /). - Split on a literal backslash:
"a\\b".split(/\\/)(double escaping needed). - Split on whitespace:
"a b\tc".split(/\s+/).
If you are unsure, start with split() and test with your data, especially checking for empty strings at the end.
Performance and Memory Considerations
For large strings, split() creates an array of substrings, which uses memory proportional to the number of splits. If you only need the first few parts, consider using indexOf() and substring() instead to avoid allocating the full array. Also, tokenize() is generally faster than split() for simple delimiters because it avoids regex compilation. If you are splitting a string in a tight loop, precompile the Pattern and pass it to split() to avoid recompiling each time. Example: def pattern = ~/,/; list.each { it.split(pattern) }.
Frequently Asked Questions
How do I split a string and keep empty values?
Use the negative limit: "a,,c".split(',', -1) returns ["a", "", "c"]. Without the -1, trailing empty strings are removed, but internal ones are kept. For example, "a,,c".split(',') returns ["a", "", "c"] because the empty string is not trailing.
What is the difference between split() and tokenize()?
split() uses regex and returns a String[]. tokenize() uses a literal delimiter string (or any of its characters) and returns a List. Also, tokenize() drops trailing empty strings and does not support regex. For example, "a.b".split('.') fails because . is a regex wildcard, but "a.b".tokenize('.') works.
Can I split on multiple characters at once?
Yes, with split() using a regex character class. For instance, "a-b_c".split(/[-_]/) splits on both hyphen and underscore. With tokenize(), you can pass a string containing all delimiters: "a-b_c".tokenize('-_') does the same, but note that it splits on any of those characters individually, not on the sequence “-_”.
Does split() modify the original string?
No, strings are immutable in Groovy (and Java). split() returns a new array of new strings; the original string remains unchanged. If you need to mutate, you would assign the result to a new variable.
How do I split a string into a list of integers?
First split into strings, then convert each element. For example: "1,2,3".split(',').collect { it as Integer } returns a list of integers. Or use "1,2,3".split(',').toList()*.toInteger().
Why does split() on a dot not work?
Because . is a regex metacharacter that matches any character. To split on a literal dot, escape it: "a.b".split(/\\./) or use tokenize('.'). Alternatively, use Pattern.quote('.') to escape it automatically: "a.b".split(Pattern.quote('.')).
Conclusion
The split() function is a powerful tool for parsing strings, but you must remember its regex nature. For simple literal delimiters, tokenize() is a convenient alternative. Always test with edge cases like trailing delimiters or special characters to avoid unexpected results.
Related
- How to Use ENUM in SQL: A Practical Guide
- Highlight Entire Row When Cell Is Selected
- Generate Random Number SAP? Explained
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- XLOOKUP Example Table: Formulas, Results, and Tips in ExcelWith product IDs in A2:A6, prices in C2:C6, and the ID to find in E2, use =XLOOKUP(E2,A2:A6,C2:C6,"Not found").…
- Excel Filter: Exclude Specific Text from ResultsIn Excel for Microsoft 365 on Windows, open the filter arrow on the column you want to check,…
- Python pandas Excel Functions: Read and Write FilesPython pandas handles Excel files mainly with read_excel() to load workbook data into a DataFrame and DataFrame.to_excel() to…
- IF vs. IFERROR in Excel: Key Differences and ExamplesIF tests a condition and returns one result when it is true and another when it is false;…
- Excel SUBTOTAL Formula for Sum: Examples and TipsTo sum a range with Excel’s SUBTOTAL function, use =SUBTOTAL(9,A2:A20); it sums visible values and automatically excludes rows…
- Excel Attendance Sheet With Time: Setup and FormulasTo make an Excel attendance sheet with time, create columns for the date, employee, scheduled start, clock-in, clock-out,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.