Zichen Ma :
why using split()
in java works differently? I want to split a version string like this: 1.2.3.4 however if I do like this: will get an empty array,, if I use split("\\.")
, it works as my expected:
String version1 = "1.2.3.4.5";
String version2 = "1.2.3.4.5.6";
String[] v1Arr = version1.split(".");
String[] v2Arr = version2.split("\\.");
System.out.println(Arrays.toString(v1Arr)); // [] why?
System.out.println(Arrays.toString(v2Arr)); // [1, 2, 3, 4, 5, 6]
String version1 = "1-2-3-4-5";
String version2 = "1-2-3-4-5-6";
String[] v1Arr = version1.split("-");
String[] v2Arr = version2.split("\\-");
System.out.println(Arrays.toString(v1Arr)); // [1, 2, 3, 4, 5]
System.out.println(Arrays.toString(v2Arr)); // [1, 2, 3, 4, 5, 6]
If I change "." to "-" both work as expected, why does this happens? Thank you in advance!
Elliott Frisch :
.
is a special pattern token in a regular expression. It matches any one character. When you split on every possible character you get an empty array (because there is nothing left). In contrast, when you escape the .
with \\.
the token is rendered as a literal (and only matches a literal .
).