我有一个字符串(line
),我想检查此字符串是否包含某个句子。此句子保存在数组(StringArray
)中。
public class example {
String line = "I`ve got a Pc";
public void test() throws Exception {
String[] StringArray = new String[1];
StringArray[0] = "Example sentence";
StringArray[1] = "Pc";
//I know this doesn´t work, but thats my problem
if (line.contains(StringArray) {
// doesn't matter what here should be
}
我将流传输数组,然后检查字符串是否包含其任何元素:
if (Arrays.stream(stringArray).anyMatch(s -> line.contains(s)) {
// Do something...
我更喜欢在这里使用正则表达式,并交替使用:
String line = "I`ve got a Pc";
String[] array = new String[2];
array[0] = "Example sentence";
array[1] = "Pc";
List<String> terms = Arrays.asList(array);
String regex = ".*\\b(?:" + String.join("|", terms) + ")\\b.*";
if (line.matches(regex)) {
System.out.println("MATCH");
}