Replace text in StringBuilder via regex

后端 未结 6 900
旧时难觅i
旧时难觅i 2021-01-19 01:33

I would like to replace some texts in StringBuilder. How to do this?

In this code I got java.lang.StringIndexOutOfBoundsException at line with mat

6条回答
  •  误落风尘
    2021-01-19 02:00

    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:

    while (matcher.find()) {
        sb.replace(matcher.start(), matcher.end(), "x");
        matcher.region(matcher.start() + "x".length(), sb.length());
    }
    

提交回复
热议问题