通过正则表达式替换StringBuilder中的文本 [英] Replace text in StringBuilder via regex
本文介绍了通过正则表达式替换StringBuilder中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想替换StringBuilder中的一些文本。怎么做?
I would like to replace some texts in StringBuilder. How to do this?
在这段代码中我得到 java.lang.StringIndexOutOfBoundsException
与<$ c $一致c> matcher.find():
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");
推荐答案
让我们拥有一个总长度为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.
这篇关于通过正则表达式替换StringBuilder中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文