Les comento que este tema me ha rondado la cabeza todo el día y ya desde hace algún tiempo me lo habia topado y le había hecho el quite, pero hoy que me he puesto a investigar que es lo que pasa. Antes que nada esta investigación se realizo con JDK 8 (1.8.0_144)
por si acaso.
- Lo primero que encontre es que cuando al método
String.split
se le pasa como parametro una expresión regular (regex
) este delega su resolución al método Pattern.split
.
El método Patter.split
crea un objeto Matcher
de acuerdo a regex
y la cadena a la cual se le aplica.
Por cada coincidencia que el Matcher encuentre al inicio de la cadena crea una subsecuencia de longitud cero (0
) que adiciona al arreglo del resultado, String match = cadena.subSequence(indexStart, indexEnd);
, donde indexStart
es igual a indexEnd
. La subsecuancia es resuelta por el método String.substring(int beginIndex, int endIndex)
.
Y es por esto que se crea el string vacio (""
), pero el método Pattern.split
no los ignora y los adiciona a arreglo de salida.
He tomado el código del método Pattern.split
y lo he modificado, de forma tal que ignore las cadenas vacias, a este metodo se le realizaron pequeños cambios
a)
Esta como método estatico
unicamente para poderlo llamar desde el método main
.
b)
Se adiciono el segundo parametro String regex
para poder crear el Matcher
.
c)
Comentariamos el Matcher
original del método con el fin de crear el propio. //Matcher m = matcher(input);
d)
creamos nuestro propio Matcher
: Pattern pa = Pattern.compile(regex); m = pa.matcher(input);
y por último adicionamos la validación para no agregar cadenas vacias al resultado
if(!match.equals("")){
matchList.add(match);
}
Dejo el metodo modificado y más abajo dejo el método original del Patter.split()
public static String[] myPatternSplit(CharSequence input, String regex, int limit) {
int index = 0;
boolean matchLimited = limit > 0;
ArrayList<String> matchList = new ArrayList<>();
//Matcher m = matcher(input); <-- comentariamos esta linea
Pattern pa = Pattern.compile(regex); // <-- adicionamos un Patter
Matcher m = pa.matcher(input); // <-- creamos un Matcher
// Add segments before each match found
while(m.find()) {
if (!matchLimited || matchList.size() < limit - 1) {
if (index == 0 && index == m.start() && m.start() == m.end()) {
// no empty leading substring included for zero-width match
// at the beginning of the input char sequence.
continue;
}
String match = input.subSequence(index, m.start()).toString();
// Adicionamos validación para no ingresar vacios
if(!match.equals("")){
matchList.add(match);
}
index = m.end();
} else if (matchList.size() == limit - 1) { // last one
String match = input.subSequence(index,
input.length()).toString();
matchList.add(match);
index = m.end();
}
}
// If no match was found, return this
if (index == 0)
return new String[] {input.toString()};
// Add remaining segment
if (!matchLimited || matchList.size() < limit)
matchList.add(input.subSequence(index, input.length()).toString());
// Construct result
int resultSize = matchList.size();
if (limit == 0)
while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
resultSize--;
String[] result = new String[resultSize];
return matchList.subList(0, resultSize).toArray(result);
}
Código original
public String[] split(CharSequence input, int limit) {
int index = 0;
boolean matchLimited = limit > 0;
ArrayList<String> matchList = new ArrayList<>();
Matcher m = matcher(input);
// Add segments before each match found
while(m.find()) {
if (!matchLimited || matchList.size() < limit - 1) {
if (index == 0 && index == m.start() && m.start() == m.end()) {
// no empty leading substring included for zero-width match
// at the beginning of the input char sequence.
continue;
}
String match = input.subSequence(index, m.start()).toString(); <-- Aca genera la cadena vacia
matchList.add(match); <-- aca la adiciona
index = m.end();
} else if (matchList.size() == limit - 1) { // last one
String match = input.subSequence(index,
input.length()).toString();
matchList.add(match);
index = m.end();
}
}
// If no match was found, return this
if (index == 0)
return new String[] {input.toString()};
// Add remaining segment
if (!matchLimited || matchList.size() < limit)
matchList.add(input.subSequence(index, input.length()).toString());
// Construct result
int resultSize = matchList.size();
if (limit == 0)
while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
resultSize--; <-- aca elimina las cadenas vacias al final del arreglo
String[] result = new String[resultSize];
return matchList.subList(0, resultSize).toArray(result);
}