How to find the exact word using a regex in Java?

前端 未结 6 1898
既然无缘
既然无缘 2020-11-30 07:01

Consider the following code snippet:

String input = \"Print this\";
System.out.println(input.matches(\"\\\\bthis\\\\b\"));

Output



        
6条回答
  •  一整个雨季
    2020-11-30 07:08

    When you use the matches() method, it is trying to match the entire input. In your example, the input "Print this" doesn't match the pattern because the word "Print" isn't matched.

    So you need to add something to the regex to match the initial part of the string, e.g.

    .*\\bthis\\b
    

    And if you want to allow extra text at the end of the line too:

    .*\\bthis\\b.*
    

    Alternatively, use a Matcher object and use Matcher.find() to find matches within the input string:

        Pattern p = Pattern.compile("\\bthis\\b");
        Matcher m = p.matcher("Print this");
        m.find();
        System.out.println(m.group());
    

    Output:

    this
    

    If you want to find multiple matches in a line, you can call find() and group() repeatedly to extract them all.

提交回复
热议问题