gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:58:23 29 4
gpt4 key购买 nike

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

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com