Replace text in StringBuilder with regex

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

In this code, I got java.lang.StringIndexOutOfBoundsException in a 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"); 
+4
source share
6 answers

Allows you to have a total StringBuilder length of w / 50, and you change the first 20chars to "x". Thus, StringBuilder is reduced by 19, to the right - however, the original pattern.matcher (sb) template does not change, so at the end of the StringIndexOutOfBoundsException.

+4
source

This is a bug already reported, and I assume that they are currently looking for a fix. More details here .

+1
source

I solved this by adding matcher.reset() :

  while (matcher.find()) { sb.replace(matcher.start(), matcher.end(), "x"); matcher.reset(); } 
+1
source

You must not do this. Matcher input can be any CharSequence, but the sequence should not be changed. Matching, like you, is like repeating a collection while deleting items at the same time, this will not work.

However, maybe there is a solution:

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

May be:

  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 asserts a reset match before it starts looking at the specified index. This will be due to issues raised in the maartinus comment above.

0
source

Another problem with using StringBuidler.replace () is that you cannot handle capture groups.

0
source

Source: https://habr.com/ru/post/1337497/


All Articles