¿Cómo dividiría una cadena sin consumir la parte del divisor?
Algo como esto, pero en su lugar : estoy usando #[a-fA-F0-9]{6} regex.
String from = "one:two:three"; String[] to = ["one",":","two",":","three"]; Ya intenté usar commons lib ya que tiene StringUtils.splitPreserveAllTokens() pero no funciona con expresiones regulares.
EDITAR: Supongo que debería haber sido más específico, pero esto es más de lo que estaba buscando.
String string = "Some text here #58a337test #a5fadbtest #123456test as well. #58a337Word#a5fadbwith#123456more hex codes."; String[] parts = string.split("#[a-fA-F0-9]{6}"); /*Output: ["Some text here ","#58a337","test ","#a5fadb","test ","#123456","test as well. ", "#58a337","Word","#a5fadb","with","#123456","more hex codes."]*/EDICIÓN 2: ¡Solución!
final String string = "Some text here #58a337test #a5fadbtest #123456test as well. #58a337Word#a5fadbwith#123456more hex codes."; String[] parts = string.split("(?=#.{6})|(?<=#.{6})"); for(String s: parts) { System.out.println(s); }Producción:
Some text here #58a337 test #a5fadb test #123456 test as well. #58a337 Word #a5fadb with #123456 more hex codes.Podría usar \\b (palabra separada, \ escapado) para dividir en su caso,
final String string = "one:two:three"; String[] parts = string.split("\\b"); for(String s: parts) { System.out.println(s); }La respuesta dada por @vrintle +1 es probablemente el código más estricto que se puede escribir para su entrada exacta. Pero, suponiendo que pueda tener otros caracteres que no sean palabras en la entrada además de : , entonces también podría dividir con mayor precisión usando las búsquedas:
String from = "one:two:three"; String[] parts = from.split("(?<=:)|(?=:)"); System.out.println(Arrays.toString(parts));Esto imprime:
[one, :, two, :, three]