我正在研究基于java和MySQL的应用程序,我的任务是检查给定字符串中存在的相邻单词集是否包含很多单词。 例如
字符串是
" java is a programing language .java is robust and powerful and it is also platform independent. "
我想检查上面字符串中是否存在子字符串
"programing language"
"platform independent"和
"robust and powerful"。即使在单词之间出现多个空格,子字符串也必须匹配。
答案 0 :(得分:1)
您可以尝试以下方式:
String string = " java is a programing language .java is robust and powerful and it is also platform independent. ";
String subS1 = "programing language";
subS1 = subS1.replace(" ", "\\s+");
Pattern p1 = Pattern.compile(subS1);
Matcher match1 = string.matcher(subS1);
String subS2 = "platform independent";
subS2 = subS2.replace(" ", "\\s+");
Pattern p2 = Pattern.compile(subS2);
Matcher match2 = string.matcher(subS2);
String subS3 = "robust and powerful";
subS3 = subS3.replace(" ", "\\s+");
Pattern p3 = Pattern.compile(subS3);
Matcher match3 = string.matcher(subS3);
if (match1.find() && match2.find() && match3.find()) {
// Whatever you like
}
你应该用' \ s +'替换子串中的所有空格,这样它也会找到"编程[whitespaces的加载]语言"。 然后编译要查找的模式并匹配字符串和子字符串。重复每个子字符串。 最后,测试匹配者是否发现了什么。
一些笔记
答案 1 :(得分:0)
你可以在问题的第一部分尝试这个问题,如果我没有理解你的问题,我也不会这样做。
String str = " java is a programing language .java is robust and powerful and it is also platform independent. ";
if (str.contains("programing language")) {
System.out.println("programing language");
}
if (str.contains("platform independent")) {
System.out.println("platform independent");
}
if (str.contains("robust and powerful")) {
System.out.println("robust and powerful");
}
我不知道你的意思是什么:即使字词之间出现多个空格,子字符串也必须匹配。