Is there a way to split strings with String.split() and include the delimiters? [duplicate]

Answer

You can use Lookahead and Lookbehind. Like this:

System.out.println(Arrays.toString("a;b;c;d".split("(?<=;)")));System.out.println(Arrays.toString("a;b;c;d".split("(?=;)")));System.out.println(Arrays.toString("a;b;c;d".split("((?<=;)|(?=;))")));

And you will get:

[a;, b;, c;, d][a,;b,;c,;d][a,;, b,;, c,;, d]

The last one is what you want.

((?<=;)|(?=;)) equals to select an empty character before ; or after ;.

Hope this helps.

EDIT Fabian Steeg comments on Readability is valid. Readability is always the problem for RegEx. One thing, I do to help easing this is to create a variable whose name represent what the regex does and use Java String format to help that. Like this:

staticpublicfinalStringWITH_DELIMITER ="((?<=%1$s)|(?=%1$s))";...publicvoid someMethod(){...finalString[] aEach ="a;b;c;d".split(String.format(WITH_DELIMITER,";"));...}...

All string Questions

Ask your interview questions on string

Write Your comment or Questions if you want the answers on string from string Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---