【问题标题】:Java Variable SubstitutionJava 变量替换
【发布时间】:2017-05-12 20:41:31
【问题描述】:

我试图找到一种替换字符串中每个$# 的方法,其中$ 是文字字符'$'# 是一个数字(1 个或多个数字),并且将$# 替换为数组中# 位置处的字符串值。

这里有一些例子:

  1. 输入 1(字符串):hello $2 输入 2(数组)dave richard danny 结果:hello richard
  2. 输入 1(字符串):hi $4 输入 2(数组)morgan ryan matthew nikoli 结果:hi nikoli

PS:我刚从 C# 转回 Java,所以我忘记了很多东西(除非是语法之类的基础知识)

当前代码:

public static String parse(String command, String[] args) {
    String substituted = "";
    substituted = command;

    return substituted;
}

我正在寻找一个可以用数组中的字符串替换表达式的函数。

【问题讨论】:

标签: java regex substitution


【解决方案1】:

这通常只使用String#replaceAll 即可解决,但由于您有自定义的动态替换字符串,您可以使用Matcher 高效简洁地进行字符串替换。

public static String parse(String command, String... args) {
    StringBuffer sb = new StringBuffer();
    Matcher m = Pattern.compile("\\$(\\d+)").matcher(command);
    while (m.find()) {
        int num = Integer.parseInt(m.group(1));
        m.appendReplacement(sb, args[num - 1]);
    }
    m.appendTail(sb);
    return sb.toString();
}

Ideone Demo

【讨论】:

  • 是的,这行得通!谢谢!你能向我解释一下它是如何工作的吗?我以前没听说过 Matcher....
  • appendReplacement 的文档包括我如何使用它的另一个示例,并解释了它的作用。
  • 干杯!对于像我这样的菜鸟,我们需要更多像你这样的人:(
  • 完美使用appendReplacement()。 +1。但是,虽然它与正则表达式无关,但我也建议将 args 参数更改为可变参数,以便更容易地使用固定的值列表进行调用。 ;-)
  • @Andreas 好主意,有点像printf 风格的方法。
【解决方案2】:

一个简单但低效的解决方案是遍历替换数组,寻找#1#2 等:

String[] arr = new String[]{"one","two","three"};
String toReplace = "first $1 second $2 third $3";
for (int i =0; i<arr.length;i++){
    toReplace = toReplace.replaceAll("\\$"+(i+1), arr[i]);
}
System.out.println(toReplace);

输出:

first one second two third three

更有效的方法是对输入字符串本身进行一次迭代。这是一个快速而肮脏的版本:

String[] arr = new String[]{"one","two","three"};
String toReplace = "first $1 second $2 third $3";
StringBuilder sb = new StringBuilder();
for (int i=0;i<toReplace.length();i++){
    if (toReplace.charAt(i)=='#' && i<toReplace.length()-1){
        int index = Character.digit(toReplace.charAt(i+1),10);
        if (index >0 && index<arr.length){
            sb.append(arr[index]);
            continue;
        }
    }
    sb.append(toReplace.charAt(i));
}
System.out.println(toReplace);

输出:

first one second two third three

【讨论】:

  • 如果“变量”出现故障,它会起作用吗?
  • 你能给我链接 Ideone 吗?我在去商店的路上。对不起!
猜你喜欢
  • 2022-01-11
  • 2011-02-17
  • 1970-01-01
  • 2014-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-15
  • 1970-01-01
相关资源
最近更新 更多