In the JavaScript pattern, you have two selection groups that are nested in one selection group, $1 references the selection-group with the other two selection groups in it.
In the Java pattern, you have two selection-groups, and no other ones, $1 references to the first selection-group instead of the one that contains the other two as in the JavaScript pattern.
Removing the braces of the first selection-group in JavaScript reproduces the unexpected result, so adding braces around the Java pattern should solve your problem.
What went wrong
The first pattern's selection-group sls
Before
//JavaScript
var str = "blue,red,green,orange,yellow,brown,black,teal,purple,gold,silver"
str = str.replace(/(([^,]*,){4}([^,]*)),/g, '$1\n').
//Output:
//blue,red,green,orange,yellow
//,brown,black,teal,purple
//,gold,silver
//Java
String str = "blue,red,green,orange,yellow,brown,black,teal,purple,gold,silver";
str = str.replaceAll("([^,]*,){4}([^,]*)", "$1\n");
//Output:
//orange,
//teal,
//,gold,silver
Regexr for Java pattern (not fixed yet)
After
//JavaScript
var str = "blue,red,green,orange,yellow,brown,black,teal,purple,gold,silver"
str = str.replace(/(([^,]*,){4}([^,]*)),/g, '$1\n').
//Output:
//blue,red,green,orange,yellow
//,brown,black,teal,purple
//,gold,silver
//Java
String str = "blue,red,green,orange,yellow,brown,black,teal,purple,gold,silver";
str = str.replaceAll("(([^,]*,){4}([^,]*)),", "$1\n");
// These were added --^------------------^^
//Output:
//blue,red,green,orange,yellow
//,brown,black,teal,purple
//,gold,silver
Regexr for Java pattern (fixed)
([^,]*,){4}so you only get the last one. What's wrong with using the same regex's?