-2

I would like to find substrings in a string based on multiple string patterns.

For example : "word1 word2 word3 and word4 word5 or word6 in word7 in word8" split based on and, or, in.

The output should be

word1 word2 word3
and word4 word5
or word6
in word7
in word8
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Ganny
  • 31
  • 5

2 Answers2

3

Use with this :

String str = "word1 word2 word3 and word4 word5 or word6 in word7 in word8";

            String[] parts = str.split("and |in |or ");

            for(String part : parts)
                System.out.println(part);
        }
Pluto
  • 853
  • 1
  • 8
  • 28
1

You can do it using look-ahead, ?= as shown below:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String str = "word1 word2 word3 and word4 word5 or word6 in word7 in word8";
        String[] arr = Arrays.stream(str.split("(?=\\s+and)|(?=\\s+or)|(?=\\s+in)"))
                        .map(String::trim)
                        .toArray(String[]::new);
        // Display
        Arrays.stream(arr).forEach(System.out::println);
    }
}

Output:

word1 word2 word3
and word4 word5
or word6
in word7
in word8
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110