I'm looking for a very simple way of getting the equivalent of something like the following JavaScript code. That is, for each match I would like to call a certain transformation function and use the result as the replacement value.
var res = "Hello World!".replace(/\S+/, function (word) { // Since this function represents a transformation, // replacing literal strings (as with replaceAll) are not a viable solution. return "" + word.length; }) // res => "5 6"
Only .. in Java. And, preferably as a "single method" or "template" that can be reused.
Your answer is in the Matcher#appendReplacement documentation. Just put your function call in the while loop.
[The appendReplacement method] is intended to be used in a loop together with the appendTail and find methods. The following code, for example, writes one dog two dogs in the yard to the standard-output stream:
Pattern p = Pattern.compile("cat"); Matcher m = p.matcher("one cat two cats in the yard"); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, "dog"); } m.appendTail(sb); System.out.println(sb.toString());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With