通过正则表达式替换StringBuilder中的文本
我想替换StringBuilder中的一些文本。 这个怎么做?
在这段代码中,我得到了与matcher.find()
一致的java.lang.StringIndexOutOfBoundsException
:
StringBuilder sb = new StringBuilder(input); Pattern pattern = Pattern.compile(str_pattern); Matcher matcher = pattern.matcher(sb); while (matcher.find()) sb.replace(matcher.start(), matcher.end(), "x");
让我们有一个总长度为50的StringBuilder,你可以将前20个变为’x’。 所以StringBuilder缩小了19,对 – 但是初始输入pattern.matcher(sb)没有改变,所以最后是StringIndexOutOfBoundsException。
这已经是一个报告的错误,我猜他们正在寻找一个修复它。 在这里阅读更多。
我通过添加matcher.reset()
解决了这个问题:
while (matcher.find()) { sb.replace(matcher.start(), matcher.end(), "x"); matcher.reset(); }
你不应该这样做。 Matcher的输入可以是任何CharSequence,但序列不应更改。 像你一样匹配就像在同时删除元素时迭代Collection,这是行不通的。
但是,也许有一个解决方案:
while (matcher.find()) { sb.replace(matcher.start(), matcher.end(), "x"); matcher.region(matcher.start() + "x".length(), sb.length()); }
也许:
int lookIndex = 0; while (lookIndex < builder.length() && matcher.find(lookIndex)) { lookIndex = matcher.start()+1; builder.replace(matcher.start(), matcher.end(), repl); }
...?
带有整数参数的.find(n)声称在开始查看指定的索引之前重置匹配器。 这将解决上面maartinus评论中提出的问题。
使用StringBuidler.replace()的另一个问题是,无法处理捕获组。