ashishgupta_mca ashishgupta_mca - 17 days ago 7
Java Question

StringUtils or any library class method to preserve the delimiter

I am having a string "role1@role2@role3@role4$arole" separated with delimiter @ and $. I used below java code

String str = "role1@role2@role3@role4$arole";
String[] values = StringUtils.splitPreserveAllTokens(str, "\\@\\$");

for (String value : values) {
System.out.println(value);
}


And got the result

role1
role2
role3
role4
arole


But my requirement is to preserve the delimiter in the result. So, the result has to be as per requirement

role1
@role2
@role3
@role4
$arole


I analyzed the apache commons StringUtils method to do that but was unable to found any clue.

Any library class to get the above intended results?

Answer

You may use a simple split with a positive lookahead:

String str = "role1@role2@role3@role4$arole";
String[] res = str.split("(?=[@$])");
System.out.println(Arrays.toString(res));
// => [role1, @role2, @role3, @role4, $arole]

See the Java demo

The (?=[@$]) regex matches any location in a string that is followed with a @ or $ symbol (note the $ does not have to be escaped inside a [...] character class).