e424. determining if a string matches a pattern exactly.txt

来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 20 行

TXT
20
字号
There are two ways to determine if a string exactly matches a regular expression. The first is to add the boundary matcher \A to the beginning and \z to the end of the pattern. The other way is to use Matcher.matches(), which does not require changes to the pattern. 
If the pattern only needs to match the beginning of the string, use Matcher.lookingAt(). 

    // Compile regular expression
    String patternStr = "b";
    Pattern pattern = Pattern.compile(patternStr);
    
    // Determine if there is an exact match
    CharSequence inputStr = "a b c";
    Matcher matcher = pattern.matcher(inputStr);
    boolean matchFound = matcher.matches(); // false
    
    // Try a different input
    matcher.reset("b");
    matchFound = matcher.matches();         // true
    
    // Determine if pattern matches beginning of input
    matchFound = matcher.lookingAt();       // false

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?