question
How to get each individual replacement result from a Regex replacement?
ex
String regexMatchedWord = matcher.group();
allows me to access the current matched result;
But is there something like String regexMatchedSubstitution = matcher.currentMatchedReplacementResult();
allows me to access the current replacement result?
public class Test {
public static void main(String[] args) {
String content_SearchOn = "Sample sentence: snake, snail, snow, spider";
String regexStrSubstitution = "$2$3$1";
String regexStrMatchFor = "(s)(.)(.)";
Matcher matcher = Pattern.compile(regexStrMatchFor).matcher(content_SearchOn);
ArrayList<String> arr_regexMatchedWord = new ArrayList<>();
ArrayList<String> arr_regexMatchedSubstitution = new ArrayList<>();
StringBuilder sb_content_Replaced = new StringBuilder();
while (matcher.find()) {
String regexMatchedWord = matcher.group();
arr_regexMatchedWord.add(regexMatchedWord);
matcher.appendReplacement(sb_content_Replaced, regexStrSubstitution);
String regexMatchedSubstitution = null; // << What should I put here -- to get each replacement result?
arr_regexMatchedSubstitution.add(regexMatchedSubstitution);
}
matcher.appendTail(sb_content_Replaced);
System.out.println(sb_content_Replaced); // Sample enstence: naske, nasil, nosw, pisder
System.out.println(arr_regexMatchedWord); // [sen, sna, sna, sno, spi]
System.out.println(arr_regexMatchedSubstitution); // [ens, nas, nas, nos, pis] // << expect
}
}
comments
- if Java is not able to do this, is there any other language able to? (Javascript? Python?)
Update: potential solution (workaround)
(as talked in the comment) A simple possible way might be:
convert those
$1
intogroup(1)
programmatically,but you have to watch out for the escape characters like
\
that has special meaning...Another way might be:
use Reflection to somehow get the local variable
result
in the source codeappendExpandedReplacement(replacement, result);
ofjava.util.regex.Matcher.appendReplacement(StringBuilder, String)
public Matcher appendReplacement(StringBuilder sb, String replacement) { // If no match, return error if (first < 0) throw new IllegalStateException("No match available"); StringBuilder result = new StringBuilder(); appendExpandedReplacement(replacement, result); // Append the intervening text sb.append(text, lastAppendPosition, first); // Append the match substitution sb.append(result); lastAppendPosition = last; modCount++; return this; }
Or:
Record the end index before the append & count from that index to get the Appended Replacement after the append.