如何检查模式是否包含java

时间:2015-12-17 12:37:47

标签: java regex string pattern-matching string-matching

我正在研究基于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"
。即使在单词之间出现多个空格,子字符串也必须匹配。

2 个答案:

答案 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");
    }

我不知道你的意思是什么:即使字词之间出现多个空格,子字符串也必须匹配。