This is a general answer to the question title; it may not directly address the specifics of the question. Let's say we have a string called PATTERN and a string called body. Then we can remove all matches of PATTERN from body as follows:
StringBuilder builder = new StringBuilder();
int x = 0;
Matcher m = Pattern.compile(PATTERN).matcher(body);
while (m.find()) {
builder.append(body.substring(x, m.start()));
x = m.end();
}
return(builder.toString());
E.g. if PATTERN = "XOX" and body = "Hello XOXWorldXOX" then we should get back "Hello World".
How it works: iterate through each match, recording the index in the string just after the last match, and adding the substring from that index to the start of the current match to a string builder, then skipping the index forward over the current match to the end. Finally, build the string.
Note: The answer of beny23 is better for removal of a regex from a string. However, with a small tweak, the above code can be made more general. It can be changed to replace each subsequent occurrence of the regex with a unique replacement string. This is more powerful and general than replaceAll, but it's an odd corner case that probably doesn't crop up that often. Still, to show you what I mean, suppose instead of removing each regex match, we want to replace the first match with "match_1" and the second with "match_2" and so on, we can do this:
StringBuilder builder = new StringBuilder();
int x = 0;
int matchNumber = 1;
Matcher m = Pattern.compile(PATTERN).matcher(body);
while (m.find()) {
builder.append(body.substring(x, m.start()));
builder.append("match_" + matchNumber);
x = m.end();
}
return(builder.toString());
E.g. if PATTERN = "XOX" and body = "Hello XOXWorldXOX" then we should get back "Hello match_1Worldmatch_2".
With a little more tweaking, we could generalise the above to replace each subsequent match with an array element, making it truly general.