当与输入匹配时包含锚($)的正则表达式在以下程序中显示意外结果,为什么?

use*_*526 1 java regex

/*
    patString: it$
    input: this is it
    the output at 2 to the match operation at 1 is false, why?
*/

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.Console;

public class Test {
    public static void main(String args[])  {
        Console con = System.console();
        String patString, input;
        patternString  = con.readLine("Enter pattern: "); //pattern 
        input =  con.readLine("input: "); // input string to match against pattern
        Pattern pattern = Pattern.compile(patString);
        Matcher matcher = pattern.matcher(input);
        boolean testMatch = matcher.matches(); //1
        System.out.println("match found: " + testMatch); //2
    }
}
Run Code Online (Sandbox Code Playgroud)

Adr*_*onk 7

Matcher.matches()方法尝试将整个字符串与给定的模式匹配,换句话说,它具有隐式^...$的模式周围.

你想要这个find()方法

来自Matcher的javadoc :

  • matcher():尝试将整个输入序列与模式匹配
  • find():尝试查找与模式匹配的输入序列的下一个子序列.