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

前端 未结 6 1929
既然无缘
既然无缘 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:21

    For a good explanation, see: http://www.regular-expressions.info/java.html

    myString.matches("regex") returns true or false depending whether the string can be matched entirely by the regular expression. It is important to remember that String.matches() only returns true if the entire string can be matched. In other words: "regex" is applied as if you had written "^regex$" with start and end of string anchors. This is different from most other regex libraries, where the "quick match test" method returns true if the regex can be matched anywhere in the string. If myString is abc then myString.matches("bc") returns false. bc matches abc, but ^bc$ (which is really being used here) does not.

    This writes "true":

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

提交回复
热议问题