在|上拆分字符串(管道)在Java中 [英] Split a String on | (pipe) in Java
问题描述
我有以下文字: ARIYALUR:ARIYALUR | CHENNAI:CHENNAI | COIMBATORE:COIMBATORE | CUDDALORE:CUDDALORE | DINDIGUL:DINDIGUL | ERODE:ERODE | KANCHEEPURAM:KANCHEEPURAM | KANYAKUMARI:KANYAKUMARI | KRISHNAGIRI:KRISHNAGIRI | MADURAI:MADURAI |纳马卡尔:纳马卡尔|尼尔吉里斯:尼尔吉里斯|佩拉姆巴卢尔:佩拉姆巴卢尔|本地治里:本地治里| SALEM:SALEM |坦贾武尔:坦贾武尔|与Theni:与Theni |蒂鲁瓦卢尔:蒂鲁瓦卢尔|杜蒂戈林:杜蒂戈林|蒂鲁内尔维利:蒂鲁内尔维利|韦洛尔:韦洛尔| VILLUPURAM :VILLUPURAM | VIRUDHUNAGAR:VIRUDHUNAGAR |
我试图做一个拆分(|)
但我的数组由单个字符组成,而不是每个区。
I tried to do a split("|")
but my array is made up of single characters and not each district.
推荐答案
|
是正则表达式中的特殊符号。请改用 \\ |
。
|
is a special symbol in regular expression. Use \\|
instead.
我会解释为什么我追加2个斜杠。要逃避 |
,我需要 \ |
。但是,要表示字符串 \ |
,\\ |
是必需的,因为 \
本身需要以字符串横向进行转义。
I'll explain why I appended 2 slashes. To escape the |
, I need \|
. However, to represent the string \|
, "\\|"
is required because \
itself needs to be escaped in a string lateral.
而且,正如xagyg在评论中指出的那样,拆分会对待该参数作为正则表达式。它不会被视为普通字符串。
And, as xagyg has pointed out in the comment, split will treat the parameter as a regular expression. It will not be treated as a plain string.
在这个用例中,您可能有兴趣了解 Pattern.quote 。你可以做 Pattern.quote(|)
。这样,所有字符都不会被视为特殊字符。
In this use case, you may be interested to learn about Pattern.quote. You can do Pattern.quote("|")
. This way, none of the characters will be treated as special ones.
这篇关于在|上拆分字符串(管道)在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!