Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 967
Lynx Avatar asked Dec 30 '22 18:12

Lynx


1 Answers

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!

like image 200
vrintle Avatar answered Jan 13 '23 15:01

vrintle