1

I almost got what I need thanks to another question on here, but not quite.

I am trying to use java's String.split() to break up a string and keep the regex delimiter. My delimiter isn't a single char. Example:

hello {world} this is {stack overflow} and this is my string

needs to break into an array like:

hello

{world}

this is

{stack overflow}

and this is my string

I am able to match all text between { and } using {[^}]+} and split a string using it. But I really need to keep the text between { and } as well.

Community
  • 1
  • 1
Sean256
  • 2,849
  • 4
  • 30
  • 39
  • Is there any particular reason that you want to use `split` for this, rather than `find`? – ruakh Jun 04 '13 at 00:14

1 Answers1

10

Try maybe splitting this way

yourString.split("\\s(?=\\{)|(?<=\\})\\s")

It will split on every space that have { after it, or space that have } before it.

Demo

String text = "hello {world} this is {Stack Overflow} and this is my string";
String[] parts = text.split("\\s(?=\\{)|(?<=\\})\\s"); 

for (String part : parts)
    System.out.println(part);

output

hello
{world}
this is
{Stack Overflow}
and this is my string
Pshemo
  • 122,468
  • 25
  • 185
  • 269