Rather far-fetched language in javadoc Pattern.splitAsStream is probably to blame.
The stream returned by this method contains each substring of the input sequence that ends with another subsequence that matches this pattern , or ends at the end of the input sequence,
If you print all matches 1,2,3,4 , you may be surprised to notice that it really returns commas , not numbers.
System.out.println("[" + pattern.splitAsStream("1,2,3,4") .collect(Collectors.joining("!")) + "]");
displays [!,!,!,] . An odd bit is why it gives you 4 , not 3 .
Obviously, this also explains why "1" gives 0 , because there are no lines in between .
Quick demo:
private void test(Pattern pattern, String s) { System.out.println(s + "-[" + pattern.splitAsStream(s) .collect(Collectors.joining("!")) + "]"); } public void test() { final Pattern pattern = Pattern.compile("\\d+"); test(pattern, "1,2,3,4"); test(pattern, "a1b2c3d4e"); test(pattern, "1"); }
prints
1,2,3,4-[!,!,!,] a1b2c3d4e-[a!b!c!d!e] 1-[]
Oldcurmudgeon
source share