Java Grails:拆分包含管道的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3842537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Grails: Splitting a string that contains a pipe
提问by Tom
I'm trying to split a String
. Simple examples work:
我正在尝试拆分String
. 简单的例子工作:
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>
采纳答案by Skip Head
You need to split on \\|
.
你需要在\\|
.
回答by mfloryan
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
或使用/
as 字符串分隔符来避免额外的转义
asserts "abc|def".split(/\|/) == ['abc','def']