java - 在 Java String.replaceAll() 正则表达式中使用函数或方法

标签 java regex string

我正在尝试将 RPN 方程转换为匹配 tigcc 规则的字符串。数字前面必须有字符数和正负标签。对于“2”,它将是“1 2 POSINT_TAG”

我对 rpn 转换器的完整输入是基于正则表达式的,所以我想再次使用它们并有一个 String.replaceAll() 函数,例如:

string.replaceAll("(\d+)","$1".length+" $1 POSINT_TAG");

但它只是打印:“2 number INT_TAG”。我找到了一些类,例如 com.stevesoft.pat ( link )。

是否有另一种在普通 Sun Java 中实现的方法来使用(自定义)函数来替换正则表达式的规则?

最佳答案

不,至少与您在 C# 或 Ruby 中执行此操作的方式不同。

最接近的是这样写一个循环:

static Pattern pattern = Pattern.compile("\\d+");
String convert(String input) {
    StringBuffer output = new StringBuffer();
    Matcher matcher = pattern.matcher(input);
    while (matcher.find()) {
        String rep =
            String.format("%d %s POSINT_TAG",
                          matcher.group().length(),
                          matcher.group());
        matcher.appendReplacement(output, rep);
    }
    matcher.appendTail(output);
    return output.toString();
}

关于java - 在 Java String.replaceAll() 正则表达式中使用函数或方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4742183/

相关文章:

java - Java 中的启动/暂停/恢复方法

java - 将xml字符串转换为java对象: getting `details` as null?

html - 提取所有 html 图像标签,Rails

C#:如何用\替换\\

linux - fgrep 和egrep ?

java - Solr 和 postgresql 集成

java - String.endsWith() 不起作用

regex - 匹配 ${.*} 的正则表达式

regex - 2 个文件包含一些相同的字符串

string - 如何匹配带小数点的数字