通过正则表达式替换 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");
I would like to replace some texts in StringBuilder. How to do this?
In this code I got java.lang.StringIndexOutOfBoundsException
at line with matcher.find()
:
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");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
让我们有一个总长度为 50 的 StringBuilder,并将前 20 个字符更改为“x”。所以 StringBuilder 缩小了 19,对吧 - 但是初始输入 pattern.matcher(sb) 没有改变,所以最终 StringIndexOutOfBoundsException。
Lets have a StringBuilder w/ 50 total length and you change the first 20chars to 'x'. So the StringBuilder is shrunk by 19, right - however the initial input pattern.matcher(sb) is not altered, so in the end StringIndexOutOfBoundsException.
我通过添加
matcher.reset()
解决了这个问题:I've solved this by adding
matcher.reset()
:这已经是一个已报告的错误,我猜他们目前正在研究解决方案。 此处了解更多信息。
This is already a reported bug and I'm guessing they're currently looking into a fix for it. Read more here.
你不应该这样做。 Matcher 的输入可以是任何 CharSequence,但序列不应更改。像你这样的匹配就像迭代一个集合,同时删除元素,这是行不通的。
不过,也许有一个解决方案:
You shouldn't do it this way. The input to Matcher may be any CharSequence, but the sequence should not change. Matching like you do is like iterating over a Collection while removing elements at the same time, this can't work.
However, maybe there's a solution:
或许:
...?
带有整数参数的 .find(n) 声称在开始查看指定索引之前重置匹配器。这将解决上面 maartinus 评论中提出的问题。
Maybe:
...?
.find(n) with an integer argument claims to reset the matcher before it starts looking at the specified index. That would work around the issues raised in maartinus comment above.
使用 StringBuidler.replace() 的另一个问题是它无法处理捕获组。
Another issue with using StringBuidler.replace() is that that one can't handle capturing groups.