【问题标题】:Find the certain word in the string [duplicate]在字符串中找到某个单词[重复]
【发布时间】:2019-02-22 21:32:21
【问题描述】:

我写了一个程序,它可以识别字符串中的某个单词,但是我有一个问题。如何识别字符串中没有空格的单词? (在一个完整的字符串中)。

String string;
    String word;

    Scanner scan = new Scanner(System.in);

    string = scan.nextLine();
    word = scan.nextLine();

    if(string.matches(".*\\b" + word +"\\b.*")){

        System.out.println("found");
    }

    else {

        System.out.println("Error");
    }

【问题讨论】:

  • 您的问题不清楚。请问您能举例说明输入和预期输出吗?
  • 为什么不使用String.contains("yourword")

标签: java string


【解决方案1】:

如果您不需要实际找到找到的确切字符串,只需将您的正则表达式部分替换为以下部分:

if(string.matches(".*" + word + ".*")){
    System.out.println("Found");
}

应该可以的。

正如其他有效指出的那样,matches 函数只是告诉字符串是否与正则表达式匹配。如果你需要检查str1是否包含str2,你应该使用contains()函数。

【讨论】:

    猜你喜欢
    • 2015-12-28
    • 1970-01-01
    • 2021-02-18
    • 1970-01-01
    • 2020-04-26
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多