Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

What is the equivalent of Regex-replace-with-function-evaluation in Java 7?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...