-3

Let's assume I have a String that contains data in square brackets. How to split content of this String using a specific word. Below I show simplified example of what I would like to do. My string:

"[Chapter 1]
[Lorem ipsum 123]
[Lorem ipsum 456]
Lorem ipsum 789
[Chapter 2]
[Lorem ipsum 012]
[Lorem ipsum 345]"

My attempt:

public void method() { 
   String myString = "[Chapter 1][Lorem ipsum 123][Lorem ipsum 456]Lorem ipsum 789[Chapter 2][Lorem ipsum 012][Lorem ipsum 345]"; 
   String []myArray = myString.split("\[Chapter"); for (String var : myArray) {          
      System.out.println(var); 
   } 
}

I want to split my String every time when "[Chapter" is present. Results of splitting:

First String:

"[Chapter 1]
[Lorem ipsum 123]
[Lorem ipsum 456]
Lorem ipsum 789"

Second String:

"[Chapter 2]
[Lorem ipsum 789]
[Lorem ipsum 012]"
Srdjan M.
  • 3,310
  • 3
  • 13
  • 34
padrian92
  • 147
  • 4
  • 16

1 Answers1

2
String str="[Chapter 1][Lorem ipsum 123][Lorem ipsum 456]Lorem ipsum 789[Chapter 2][Lorem ipsum 012][Lorem ipsum 345]";
String str1[]=str.split("(?=\\[Chapter )");
for(String s : str1)
System.out.println(s);

Demo Link

https://repl.it/repls/NavyblueBetterJavadoc

Jay Shankar Gupta
  • 5,918
  • 1
  • 10
  • 27