Find and replace Java regular expressions

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;
  // pseudo-code:
  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.

+4
2

Matcher.replaceFirst, , replaceFirst. Matcher: appendReplacement appendTail. find:

StringBuffer sb = new StringBuffer();
matcher.appendReplacement(sb, replacement);
matcher.appendTail(sb);

Stringbuffer , , String ( )

+1

, find() start() end().

StringBuilder builder = new StringBuilder(stringToMatch);
Matcher m = Pattern.compile(yourRegex).matcher(stringToMatch);
for (int i = 0 ; i < n ; i++) { // n is the nth match you want to replace
    m.find();
}
builder.replace(m.start(), m.end(), yourReplacement);
+6

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


All Articles