我正在尝试使用正则表达式删除 nbsp;从我的绳子上。以下是程序。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MyTest {
private static final StringBuffer testRegex =
new StringBuffer("<FONT style=\"BACKGROUND-COLOR: #ff6600\">Test</font></p><br><p>" +
"<FONT style=\"BACKGROUND-COLOR: #ff6600\">Test</font></p><br><p>" +
"<FONT style=\"BACKGROUND-COLOR: #ff6600\">Test</font>" +
"<BLOCKQUOTE style=\"MARGIN-RIGHT: 0px\" dir=ltr><br><p>Test</p><strong>" +
"<FONT color=#333333>TestTest</font></strong></p><br><p>Test</p></blockquote>" +
"<br><p>TestTest</p><br><BLOCKQUOTE style=\"MARGIN-RIGHT: 0px\" dir=ltr><br><p>" +
"<FONT style=\"BACKGROUND-COLOR: #ffcc66\">TestTestTestTestTest</font><br>" +
"<p>TestTestTestTest</p></blockquote><br><p>" +
"<FONT style=\"BACKGROUND-COLOR: #003333\">TestTestTest</font></p><p>" +
"<FONT style=\"BACKGROUND-COLOR: #003399\">TestTest</font></p><p> </p>");
//"This is test<P>Tag 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("<[^>]+? [^<]+?>");
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(" "," ");
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,并且当您替换
时与 ,末尾将指向无效位置,然后
find
方法会抛出 StringIndexOutOfBoundsException
如果 end 指向字符串长度之外的位置,则异常。
如果字符串很大,重置可能会导致主要的性能瓶颈,因为 reset
将再次从头开始匹配。您可以改为使用
matcher.region(start,sample.length());
这将从最后一个匹配的位置开始匹配!
关于java.lang.StringIndexOutOfBoundsException : from java. util.regex.Matcher,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16161365/