When writing a text editor with the search and replace function, the user has the ability to search several times, and then is replaced. In Java, the search part is pretty simple:
Pattern pattern = Pattern.compile(userInput);
...
String line = ...
Matcher matcher = pattern.matcher(line);
int from = 0;
while (from < line.length() && matcher.find(from)) {
int start = matcher.start();
int length = matcher.end() - start;
if (askUser()) {
return ...
}
from = start + 1;
}
But how to handle replacing the nth match? Matcherhas replaceAlland replaceFirst. The first one is obviously not suitable, but for replaceFirstthe documentation it says:
Replaces the first subsequence of the input sequence that matches the pattern with this replacement. This method first flushes this match. He then scans the input sequence, looking for a match for the pattern.
where a bold sentence makes me worry if that would be appropriate here. I will need something to replace the current match with a specific pattern.