Java 获取了具有字符串操作的任务。matcher.find()抛出boundexc,matcher.find(0)工作正常。。。为什么呢?

Java 获取了具有字符串操作的任务。matcher.find()抛出boundexc,matcher.find(0)工作正常。。。为什么呢?,java,string,matcher,Java,String,Matcher,任务是从句子中删除字母i public static void main(String[] args) { int index = 8; String letter = "i"; String text = "method appends the string to the end. t is overloaded to have the following forms."; StringBuffer sb = new StringBuffer(text);

任务是从句子中删除字母i

public static void main(String[] args) {

    int index = 8;
    String letter = "i";
    String text = "method appends the string to the end. t is overloaded to have the following forms.";
    StringBuffer sb = new StringBuffer(text);
    Pattern pat = Pattern.compile(letter);
    Matcher mat = pat.matcher(sb);

   //while (mat.find()) -throws StringIndexOutOfBoundsException. 
    while (mat.find(0)){
        sb.deleteCharAt(mat.start());
    }

    System.out.println(sb.toString());
}

好的,程序可以运行,但我不明白为什么显而易见的方法不起作用?

您必须使用
mat.reset()
方法,因为当您删除字符时,matcher知道的字符串长度将变为无效,您必须为此重置matcher

发生的情况如下:创建匹配器并将原始长度为假设5的字符串传递给它,现在在调用
find
后,将从缓冲区中删除一个字符,这将使匹配器的状态无效,因为新长度将为4。因此,有必要进行重置

为什么
find(0)
有效

答案就在源头,

来自JDK1.6的方法

public boolean find(int start) {
        int limit = getTextLength();
        if ((start < 0) || (start > limit))
            throw new IndexOutOfBoundsException("Illegal start index");

        reset(); //reset is called here
        return search(start);
}
公共布尔查找(int start){
int limit=getTextLength();
如果((开始<0)| |(开始>限制))
抛出新IndexOutOfBoundsException(“非法开始索引”);
reset();//这里调用reset
返回搜索(开始);
}

我已经给出了为什么find(0)有效而find()无效的原因。