Based on your current edit it looks like you want to split on place which is either
- directly before
{
- directly after
}
In that case you can use split
method which supports regex (regular expression). Regex provides lookaround mechanisms like
(?=subregex)
to see if we are directly before something which can be matched by subregex
(?<=subregex)
to see if we are directly after something which can be matched by subregex
Also {
and }
are considered regex metacharacters (we can use them like {m,n}
to describe amount of repetitions like a{1,3}
can match a
, aa
, aaa
but not aaaa
or more) so to make it normal literal we need to escape it like \{
and \}
Last thing you need is OR
operator which is represented as |
.
So your code can look like:
String str = "a{b}c{d}";
String[] arr = str.split("(?=\\{)|(?<=\\})"); // split at places before "{" OR after "}"
for (String s : arr){
System.out.println(s);
}
Output:
a
{b}
c
{d}
Demo: https://ideone.com/FdUbKs