views:

82

answers:

2

Hi,

Im trying to split a string. Simple examples work

groovy:000> print "abc,def".split(",");
[abc, def]===> null
groovy:000>

Instead of a comma, I need to split by pipes, but i'm not getting the desired result.

groovy:000> print "abc|def".split("|");
[, a, b, c, |, d, e, f]===> null
groovy:000>

Of course, my first choice would be to switch from pipe | to comma , as a delimeter, but now I'm intrigued.

Why is this not working? Escaping the pipe \| doesn't seem to help.

groovy:000> print "abc|def".split("\|");
ERROR org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed, groovysh_parse: 1: unexpected char: '\' @ line 1, column 24.
   print "abcdef".split("\|");
                          ^

1 error
|
        at java_lang_Runnable$run.call (Unknown Source)
groovy:000>

Thanks in advance

+4  A: 

You need to split on \\|.

Skip Head
Could you provide an example? Isn't it the same as the last code snippet I provided?
Tom
@Tom, it was a formatting problem, he meant `\\|`. You need to escape the `\ ` in order to have it interpreted in the String, so it can escape the `|`
Colin Hebert
@Skip @Colin Thank you very much. Didn't catch that formatting problem. My apologies.
Tom
@Colin: Thanks for fixing that for me.
Skip Head
+3  A: 

You have to escape pipe as, indeed, it has a special meaning in the regular expression. However, if you use quotes, you have to escape the slash as well. Basically, two options then:

asserts "abc|def".split("\\|") == ['abc','def']

or using the / as string delimiter to avoid extra escapes

asserts "abc|def".split(/\|/) == ['abc','def']
mfloryan
Thanks! The `/` seems perly and familiar :)
Tom