我想基于多个字符串模式在字符串中找到子字符串。
例如:"word1 word2 word3 and word4 word5 or word6 in word7 in word8"
根据{{1}},and
,or
进行划分。
输出应为
in
答案 0 :(得分:3)
与此配合使用:
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);
}
答案 1 :(得分:1)
您可以使用前瞻?=
进行操作,如下所示:
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);
}
}
输出:
word1 word2 word3
and word4 word5
or word6
in word7
in word8