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

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

    You may use groups to find the exact word. Regex API specifies groups by parentheses. For example:

    A(B(C))D

    This statement consists of three groups, which are indexed from 0.

    • 0th group - ABCD
    • 1st group - BC
    • 2nd group - C

    So if you need to find some specific word, you may use two methods in Matcher class such as: find() to find statement specified by regex, and then get a String object specified by its group number:

    String statement = "Hello, my beautiful world";
    Pattern pattern = Pattern.compile("Hello, my (\\w+).*");
    Matcher m = pattern.matcher(statement);
    m.find();
    System.out.println(m.group(1));
    

    The above code result will be "beautiful"

提交回复
热议问题