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()); }
source share