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");
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.
I've solved this by adding matcher.reset()
:
while (matcher.find())
{
sb.replace(matcher.start(), matcher.end(), "x");
matcher.reset();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With