1

I have a String

String value ="Caused by:null pointer exception Caused by
                             : BeanCreationException.. WARNING: its just a warning..";

I would like to split String after keywords "Caused by:" and "WARNING:" so that I have output like

  • null pointer exception
  • BeanCreationException..
  • its just a warning..

Any help would be much appreciated.

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
Alok Pathak
  • 875
  • 1
  • 8
  • 20

6 Answers6

3

You can use Caused by: or WARNING: as your delimiters

Code:

String value ="Caused by:null pointer exception Caused by"
        + ": BeanCreationException.. WARNING: its just a warning..";
String[] sp = value.split("Caused by:|WARNING:");
Stream.of(sp).forEach(s -> System.out.println(s));

Output:

 null pointer exception 
 BeanCreationException.. 
 its just a warning..

Note: some part of code is in Java 8

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
1

try using split() method

String str="Caused by:null pointer exception Caused by: BeanCreationException.. WARNING: its just a warning..";

String split[]=str.split("Caused by");

split() will return a array containing words before and after the split trem

Nishad K Ahamed
  • 1,374
  • 15
  • 25
1

You want to treat multiple substrings as separators. So my approach would be to transform all my separator substrings to a common separator, then split it by that separator.

String value ="Caused by:null pointer exception Caused by BeanCreationException.. WARNING: its just a warning..";

//Transforming substrings to a common separator
value = value.replace("Caused by:", "||");
value = value.replace("WARNING:", "||");

//Just splitting the string by separator
String valueArray = value.split("||");
Aycan Yaşıt
  • 2,106
  • 4
  • 34
  • 40
1

You can use |(OR) in #split method

value.split("Caused by:|WARNING:")

NOTE:It will give you first element empty in array if your String starts with Caused by: or WARNING: so be careful with that.

akash
  • 22,664
  • 11
  • 59
  • 87
0

You can use String.split(REQUIRED_SEPARATOR) or new StringTokenizer(inputString, "REQUIRED_SEPARATOR")

While using the StringTokenizer, you can iterate through the tokens by using hasMoreElements() and use nextToken() to access tokens.

Pramod Karandikar
  • 5,289
  • 7
  • 43
  • 68
0

Try using String.indexOf("Caused by:") to find all occurences of Caused by: then String.indexOf("WARNING:") to find all warnings.

Alexander Vasin
  • 156
  • 1
  • 7