Replace text in StringBuilder via regex

后端 未结 6 868
旧时难觅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:09

    Maybe:

        int lookIndex = 0;
        while (lookIndex < builder.length() && matcher.find(lookIndex)) {
            lookIndex = matcher.start()+1;
            builder.replace(matcher.start(), matcher.end(), repl);
        }
    

    ...?

    .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.

提交回复
热议问题