我从匹配点查找中获取indexoutofbound异常

问题描述 投票:1回答:1

面临错误,仅当我的两个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="";
java regex
1个回答
1
投票

即使您没有在数组中添加任何内容,您也可以增加计数器(i)。下次尝试访问当前项目时,索引过大,导致显示IndexOutOfBoundException

© www.soinside.com 2019 - 2024. All rights reserved.