1

我需要通过应用特定的替换方法来替换文本中的所有单词Modify()。我在 C# 中有以下代码片段:

Regex regex = new Regex("[A-Za-z][a-z]*");
regex.Replace(text, x => Modify(x.Value));

Modify()函数是执行以修改每个匹配项的一些函数,例如它可以用下一个字母字符替换单词中的所有字符。例如,如果这是输入文本:

神奇的香蕉正在吃苹果。

这可能是输出:

Nbhjd cbobob jt fbujoh uif bqqmf。

Modify() 函数的用途在这里无关紧要。我想知道MatchEvaluator的 Java 实现。代码在 C# 中相当简单,但如何在 Java 中实现呢?

4

1 回答 1

6

沿着这条线的东西怎么样:

public static void main(String[] args) {
    String text = "Magic banana is eating the apple.";
    System.out.println("Old text: " + text);
    System.out.println("New text: " + getEditedText(text));
}

private static String getEditedText(String text) {
    StringBuffer result = new StringBuffer();
    Pattern pattern = Pattern.compile("[A-Za-z][a-z]*");
    Matcher matcher = pattern.matcher(text);
    while (matcher.find()) {
        matcher.appendReplacement(result, getReplacement(matcher));
    }
    matcher.appendTail(result);
    return result.toString();
}

private static String getReplacement(Matcher matcher) {
    String word = matcher.group(0);
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < word.length(); i++) {
        char c = word.charAt(i);
        sb.append((char)(c + 1));
    }
    return sb.toString();
}

这是可以在本页底部找到的代码的略微编辑示例。

这是您将得到的输出:

Old text: Magic banana is eating the apple.
New text: Nbhjd cbobob jt fbujoh uif bqqmf.
于 2013-12-22T19:13:42.973 回答