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?

0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.