Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

259
Vistas
How to split string using regex without consuming the splitter part?

How would I split a string without consuming the splitter part?
Something like this but instead : I'm using #[a-fA-F0-9]{6} regex.

String from = "one:two:three";
String[] to  = ["one",":","two",":","three"];

I already tried using commons lib since it has StringUtils.splitPreserveAllTokens() but it does not work with regex.

EDIT: I guess I should have been more specific, but this is more of what I was looking for.

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."]*/

EDIT 2: Solution!

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);
}

Output:

Some text here 
#58a337
test 
#a5fadb
test 
#123456
test as well. 
#58a337
Word
#a5fadb
with
#123456
more hex codes.
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You could use \\b (word-break, \ escaped) to split in your case,

final String string = "one:two:three";
    
String[] parts = string.split("\\b");
for(String s: parts) {
    System.out.println(s);
}

Try it online!

over 4 years ago · Santiago Trujillo Denunciar

0

The answer given by @vrintle +1 is probably the tightest code which can be written for your exact input. But, assuming you might have other non word characters in the input besides :, then you could also split more precisely using lookarounds:

String from = "one:two:three";
String[] parts = from.split("(?<=:)|(?=:)");
System.out.println(Arrays.toString(parts));

This prints:

[one, :, two, :, three]
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda