Find the certain word in the string

时间:2018-09-18 19:33:28

标签: java string

I write program, which can recognize the certain word in the string, but i have a question. How to recognize a word in the string without gaps? (in one full string).

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

1 个答案:

答案 0 :(得分:-1)

If you don't need to actually get the exact string found, just replace your regex part with the following one:

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

That should work.

As other validly pointed out, the matches function just tells whether the string matches the regex. If you need to check whether str1 contains str2, you should use contains() function.