这是我在给定字符串中查找“ab”
模式的代码。
import java.util.regex.*;
public class RegExp
{
public static void main(String[] args)
{
Pattern p = Pattern.compile("ab");
Matcher m = p.matcher("ababbaba");
while(m.find())
{
System.out.println(m.start());
}
}
}
但我无法理解 find()
和 start()
的内部工作原理。
最佳答案
find
方法扫描输入序列,查找与模式匹配的下一个子序列,并返回一个 boolean
指示成功或失败。
内部find
方法调用search
方法(访问控制默认),以便启动搜索以在给定范围内查找Pattern
。每次匹配时,界限都会增加,直到找到所有匹配项。
在 Matcher
类后面是一个保存匹配状态的状态机。
另一方面,start
方法以最新匹配捕获的子序列的 int
形式返回起始索引。
如果您想真正深入了解,我建议您查看 source code Matcher
类。
关于java - 正则表达式查找方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43230582/