Grails:拆分包含管道的字符串

Tom*_*Tom 30 java regex grails groovy split

我正试图分裂一个String.简单的例子工作:

groovy:000> print "abc,def".split(",");
[abc, def]===> null
groovy:000>
Run Code Online (Sandbox Code Playgroud)

但是,我需要将它拆分为管道,而不是逗号,而且我没有获得所需的结果:

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

所以当然我的第一选择是从pipes(|)切换到逗号(,)作为分隔符.

但现在我很好奇:为什么这不起作用?逃离管道(\|)似乎没有帮助:

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>
Run Code Online (Sandbox Code Playgroud)

Ski*_*ead 58

你需要拆分\\|.


mfl*_*yan 19

你必须逃避管道,事实上,它在正则表达式中具有特殊含义.但是,如果使用引号,则还必须转义斜杠.基本上,有两个选择:

asserts "abc|def".split("\\|") == ['abc','def']
Run Code Online (Sandbox Code Playgroud)

或使用/as字符串分隔符来避免额外的转义

asserts "abc|def".split(/\|/) == ['abc','def']
Run Code Online (Sandbox Code Playgroud)