Java Regex Pattern Matcher.matches() before Matcher.find() 奇怪的行为

标签 java regex

我试过这个例子,只是交换了两条线,它给出了不同的输出,为什么

String inputString = "username@gmail.com"; 
String pattern="([a-z]+@)([a-z]+)(\\.[a-z]+)";
Pattern p = Pattern.compile(pattern); 
Matcher m = p.matcher(inputString); 

///变化发生在这里

if(m.find()) 
{
   String resultString = m.replaceAll("$1xxxx$3"); 
   System.out.println(resultString); 
}

System.out.println(m.matches());//line to be changed

输出:

用户名@xxxx.com

正确

System.out.println(m.matches());//line changed     
if(m.find()) 
{
   String resultString = m.replaceAll("$1xxxx$3"); 
   System.out.println(resultString); 
}

输出: 是的

最佳答案

摘自Matcher.find文档

find

public boolean find()

Attempts to find the next subsequence of the input sequence that matches the pattern. This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.

If the match succeeds then more information can be obtained via the start, end, and group methods.

Returns: true if, and only if, a subsequence of the input sequence matches this matcher's pattern

因此,由于您调用了试图匹配整个字符串的 Matcher.matches,并且您没有重置匹配器,因此它会尝试在第一个匹配项之后开始查找。由于只有一个匹配项,因此找不到任何内容。

关于Java Regex Pattern Matcher.matches() before Matcher.find() 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13362182/

相关文章:

Java DNSLookup MX 记录列表。喜欢 MXToolBox

java - 如何在以下示例代码中使用分页(限制/偏移)从选择查询中检索 block 中的数据?

regex - netsh 结果到 PowerShell 对象

java - JVM字节码验证者的职责

java - 在 Java 中创建方法并测试类

java - htmlUnit - 如何获取非元素内容

javascript - 检测字符串中的数字 - javascript regex

php - 北美编号计划正则表达式

php - 即使 strlen 在可接受的范围内,此正则表达式也会截断字符串中的最后一个单词

java - Java 中类似 Lisp 的字符串匹配