3

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?

ashishgupta_mca
  • 578
  • 6
  • 27

1 Answers1

3

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).

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563