首页 > 解决方案 > 我从匹配器点找到 indexoutofbound 异常

问题描述

我面临一个错误,我的代码只有在我的两个 RegEx(我的 RegEx 正在寻找 Text1)没有彼此相邻的情况下才有效。例如,我有一个text ="Text1, Text2, Text3"-> 一切正常。如果我有这样的东西="Text1, Text1, Text2, Text3"-> 我的代码会抛出一个IndexOutOfBoundsException.

我认为它与某些东西有关,matcher.find()但我无法弄清楚它究竟是如何工作的。

int i = 0;
while(matcher.find()) {
    if(!array.contains(matcher.group())){
        try {
                    array.add(i, matcher.group());
                    array.set(i, array.get(i).replaceAll("\\.",""));
                    array.set(i, array.get(i).replaceAll("\\W","-"));

        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    i++;
}
result="";

标签: javaregex

解决方案


i即使您没有向数组中添加任何内容,您也会增加您的计数器 ( )。下次您尝试访问当前项目时,您的索引太大,导致IndexOutOfBoundException.


推荐阅读