我正在尝试将 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/