[英]java string split is not giving expected result
I'm trying to split a string into a string [] but im not getting the expected result. 我正在尝试将字符串拆分为字符串[],但即时通讯未得到预期的结果。 What is wrong here?
怎么了
String animals = "dog|cat|bear|elephant|giraffe";
String[] animalsArray = animals.split("|");
I would expect that animalsArray contained the following: 我希望animalsArray包含以下内容:
animalsArray[0] = "dog"
animalsArray[1] = "cat"
animalsArray[2] = "bear"
...
but it contains only: 但它仅包含:
animalsArray[0] = "d"
animalsArray[1] = "c"
animalsArray[2] = "b"
...
String.split()
splits around a regular expression, not just an ordinary string so you have to escape the "|" String.split()
拆分正则表达式,而不仅仅是普通字符串,因此您必须转义“ |” (because it has special meaning) and do it as follows: (因为它具有特殊含义),并按以下步骤操作:
split("\\|")
The split
method takes a regular expression as its argument, and |
split
方法将正则表达式作为其参数,并且|
has special meaning. 有特殊的意义。 Escape it with a backslash, and escape the backslash itself for Java:
使用反斜杠对其进行转义,并针对Java转义反斜杠本身:
String[] animalsArray = animals.split("\\|");
This page lists special symbols in Java regular expressions. 该页面列出了Java正则表达式中的特殊符号。 Look for
|
寻找
|
in the "Logical Operators" section. 在“逻辑运算符”部分中。
Have a try using \\\\|
尝试使用
\\\\|
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String animals = "dog|cat|bear|elephant|giraffe";
String[] animalsArray = animals.split("\\|");
System.out.println(Arrays.toString(animalsArray));
}
}
Output in Console: 在控制台中输出:
[dog, cat, bear, elephant, giraffe]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.