Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace text in StringBuilder via regex

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"); 
like image 428
bltc Avatar asked Jan 28 '11 15:01

bltc


2 Answers

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.

like image 138
bestsss Avatar answered Oct 20 '22 00:10

bestsss


I've solved this by adding matcher.reset():

    while (matcher.find())
    {
        sb.replace(matcher.start(), matcher.end(), "x");
        matcher.reset();
    }
like image 20
bltc Avatar answered Oct 20 '22 00:10

bltc