gpt4 book ai didi

java.lang.StringIndexOutOfBoundsException : from java. util.regex.Matcher

转载 作者:行者123 更新时间:2023-12-01 14:39:10 26 4
gpt4 key购买 nike

我正在尝试使用正则表达式删除 nbsp;从我的绳子上。以下是程序。

    import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyTest {

private static final StringBuffer testRegex =
new StringBuffer("<FONT&nbsp;style=\"BACKGROUND-COLOR:&nbsp;#ff6600\">Test</font></p><br><p>" +
"<FONT&nbsp;style=\"BACKGROUND-COLOR:&nbsp;#ff6600\">Test</font></p><br><p>" +
"<FONT&nbsp;style=\"BACKGROUND-COLOR:&nbsp;#ff6600\">Test</font>" +
"<BLOCKQUOTE&nbsp;style=\"MARGIN-RIGHT:&nbsp;0px\"&nbsp;dir=ltr><br><p>Test</p><strong>" +
"<FONT&nbsp;color=#333333>TestTest</font></strong></p><br><p>Test</p></blockquote>" +
"<br><p>TestTest</p><br><BLOCKQUOTE&nbsp;style=\"MARGIN-RIGHT:&nbsp;0px\"&nbsp;dir=ltr><br><p>" +
"<FONT&nbsp;style=\"BACKGROUND-COLOR:&nbsp;#ffcc66\">TestTestTestTestTest</font><br>" +
"<p>TestTestTestTest</p></blockquote><br><p>" +
"<FONT&nbsp;style=\"BACKGROUND-COLOR:&nbsp;#003333\">TestTestTest</font></p><p>" +
"<FONT&nbsp;style=\"BACKGROUND-COLOR:&nbsp;#003399\">TestTest</font></p><p>&nbsp;</p>");

//"This&nbsp;is&nbsp;test<P>Tag&nbsp;Tag</P>";

public static void main(String[] args) {
System.out.println("***Testing***");
String temp = checkRegex(testRegex);
System.out.println("***FINAL = "+temp);

}

private static String checkRegex(StringBuffer sample){
Pattern pattern = Pattern.compile("<[^>]+?&nbsp;[^<]+?>");
Matcher matcher = pattern.matcher(sample);
while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
String group = matcher.group();
System.out.println("start = "+start+" end = "+end+"" +"***GROUP = "+group);

String substring = sample.substring(start, end);
System.out.println(" Substring = "+substring);
String replacedSubString = substring.replaceAll("&nbsp;"," ");
System.out.println("Replaced Substring = "+replacedSubString);

sample.replace(start, end, replacedSubString);
System.out.println(" NEW SAMPLE = "+sample);

}
System.out.println("********WHILE OVER ********");
return sample.toString();
}

}

我在 while (matcher.find()) 行收到 java.lang.StringIndexOutOfBoundsException。我目前正在使用 java Pattern 和 Matcher 来查找 nbsp;并将其替换为 ""。有谁知道是什么原因造成的?我应该怎么做才能删除多余的nbsp;来 self 的字符串?

谢谢

最佳答案

使用matcher.reset();之后sample.replace(start, end, replacedSubString);

这是因为当您替换字符串 sample 时,end会指向一个无效位置。因此,您需要使用 matcher.reset();每次replace之后.

例如,如果开始为 0,结束为 5,并且当您替换 &nbsp; 时与 ,末尾将指向无效位置,然后 find方法会抛出 StringIndexOutOfBoundsException如果 end 指向字符串长度之外的位置,则异常。

<小时/>

如果字符串很大,重置可能会导致主要的性能瓶颈,因为 reset将再次从头开始匹配。您可以改为使用

 matcher.region(start,sample.length());

这将从最后一个匹配的位置开始匹配!

关于java.lang.StringIndexOutOfBoundsException : from java. util.regex.Matcher,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16161365/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com