Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails: Splitting a string that contains a pipe

I’m trying to split a String. Simple examples work:

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

But instead of a comma, I need to split it on pipes, and I’m not getting the desired result:

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

So of course my first choice would be to switch from pipes (|) to commas (,) as delimiters.

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> 
like image 416
Tom Avatar asked Oct 01 '10 19:10

Tom


People also ask

How do you split a string with symbols?

One way we can use this is to use a backslash \ . For example: string. split("\\|");


1 Answers

You need to split on \\|.

like image 66
Skip Head Avatar answered Sep 24 '22 10:09

Skip Head