I'm trying to go through a string and replace all instances of a regex-matching string. For some reason when I use if
then it will work and replace just one string instance of a regex-match. When I change the if
to while
then it does some weird replacement over itself and makes a mess on the first regex-matching string while not even touching the others...
pattern = Pattern.compile(regex);
matcher = pattern.matcher(docToProcess);
while (matcher.find()) {
start = matcher.start();
end = matcher.end();
match = docToProcess.substring(start, end);
stringBuilder.replace(start, end, createRef(match));
docToProcess = stringBuilder.toString();
}
Not sure exactly what problem you got but maybe this example will help a little:
I want to change names in sentence like:
We can do this with little help of appendReplacement and appendTail methods from
Matcher
classOutput:
Aside from the sysouts I only added the last assignment. See if it helps:
If createRef(match) returns a string which is not the same length as (end - start) then the indexes you are using in docToProcess.substring(start, end) will potentially overlap.