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

后端 未结 4 1984
终归单人心
终归单人心 2020-12-01 12:07

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

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 12:59

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

提交回复
热议问题