我剛開始在工作中使用Java正則表達式,並且在使用Matcher find()方法時遇到了問題。匹配find()方法返回StringOutOfBounds異常
在下面的代碼中,我是從客戶端接收到的字符串參數,'list'是一個帶有字符串值的現成鏈接列表,我想在列表中找到最小值可能的索引超出所有其他列表值(如果確實匹配)。列表中的值可能在其末尾有一個星號,這意味着它們有一個通配符,所以在它們的末尾有0個或更多'單詞字符' - 所以我必須考慮在我搜索時。下面是代碼:
Pattern checkRegex;
int tStart = i.length();
for (String t : list){
if (t.charAt(t.length()-1) == '*')
checkRegex = Pattern.compile("\\W" + t + "[0-9A-Za-z]*\\W");
else
checkRegex = Pattern.compile("\\W" + t + "\\W");
Matcher regexMatcher = checkRegex.matcher(i);
if (regexMatcher.find()){
if (tStart > i.indexOf(regexMatcher.regionStart()))
tStart = i.indexOf(regexMatcher.regionStart());
}
我得到的錯誤 - 例外在線程「主要」 java.lang.StringIndexOutOfBoundsException:字符串索引超出範圍:-1
調試後,我發現,程序崩潰在regexMatcher.find()命令 - 但由於它是一個布爾方法,我不明白什麼字符串索引必須在這裏做。
感謝您的幫助。
看看這個鏈接:http://stackoverflow.com/questions/4829908/replace-text-in-stringbuilder-via-regex也許可以幫助你 – 2014-09-23 13:22:48
你能提供完整的堆棧跟蹤嗎? – kofemann 2014-09-23 14:21:01
不使用括號不*使你更聰明。 – drewmoore 2014-09-23 14:24:36