D. Ataro D. Ataro - 4 months ago 10x
Java Question

Splitting string in between two characters in Java

I am currently attempting to interpret some code I wrote for something. The information I would like to split looks something like this:


What I am trying to accomplish, is splitting above string in between '}' and 'T' (T, which could be any letter). The result I am after is (in pseudocode):

["{hey=yes}", "TEST"]

How would one go about doing so? I know basic regex, but have never gotten into using it to split strings in between letters before.


In order to split the string I am using the String.split method. Do tell if there is a better way to go about doing this.


You can use String's split method, as follow:

String str = "{hey=foo}TEST";
String[] split = str.split("(?<=})");       
System.out.println(split[0] + ", " + split[1]);

It splits the string and prints this:

{hey=foo}, TEST

The '?<=}', is to split after the character '}' AND keep the character while doing it. By default, if you just split on a character (ie: '}'), this character will be removed by the split. This other answer provides a complete explanation of all options when using the split method: how-to-split-string-with-some-separator-but-without-removing-that-separator-in-j