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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With