I am trying to perform a split similar the following:
println \"Hello World(1)\".split(\"W\");
Output:
[Hello , orld(1)]
Since split just accept regex, you have to pass to it as an escaped character. For this, you must append a backslash in front of it
\(
But above has a compile error because it is parsed as a valid escaped character such as:
\t Tab
\n New Line or Line Feed
\r Carriage Return
So, you must pass a non meaning character (E.g. parenthesis) with 2 backslashes:
\\(
Finally:
println "Hello World(1)".split("\\(");
OR you can also do all things by java builtin function of class Pattern named quote:
println "Hello World(1)".split(Pattern.quote("("));
println "Hello World(1)".split("\\(");
you have to escape the bracket character properly
println "Hello World(1)".split("\\(")
The split
method takes a regular expression pattern.
If you want to split on "just a regular string" you can use Pattern.quote
to quote the string first:
println "Hello World(1)".split(Pattern.quote("("))
You can also use a single escape when using groovy native regex syntax:
assert "Hello World(1)".split(/\(/) == ["Hello World", "1)"]