【问题标题】:Replacing variable placeholders in a string替换字符串中的变量占位符
【发布时间】:2012-05-11 20:15:37
【问题描述】:

我的字符串看起来像这样:“您可以在 [ 开始日期 + 30] 之前使用促销活动”。我需要用实际日期替换 [ Start Date + 30] 占位符 - 这是销售的开始日期加上 30 天(或任何其他数字)。 [Start Date] 也可以单独出现而无需添加数字。此外,占位符内的任何额外空格都应被忽略,并且不会导致替换失败。

在 Java 中最好的方法是什么?我正在考虑查找占位符的正则表达式,但不确定如何进行解析部分。如果只是 [Start Date] 我会使用 String.replaceAll() 方法,但我不能使用它,因为我需要解析表达式并添加天数。

【问题讨论】:

  • 查看 MessageFormat.format javadocs,我想它是最适合进行文本替换的类。

标签: java regex string replace


【解决方案1】:

你应该使用StringBufferMatcher.appendReplacementMatcher.appendTail

这是一个完整的例子:

String msg = "Hello [Start Date + 30] world [ Start Date ].";
StringBuffer sb = new StringBuffer();

Matcher m = Pattern.compile("\\[(.*?)\\]").matcher(msg);

while (m.find()) {

    // What to replace
    String toReplace = m.group(1);

    // New value to insert
    int toInsert = 1000;

    // Parse toReplace (you probably want to do something better :)
    String[] parts = toReplace.split("\\+");
    if (parts.length > 1)
        toInsert += Integer.parseInt(parts[1].trim());

    // Append replaced match.
    m.appendReplacement(sb, "" + toInsert);
}
m.appendTail(sb);

System.out.println(sb);

输出:

Hello 1030 world 1000.

【讨论】:

  • 出于某种原因,我不得不使用 m.group(0) 而不是 m.group(1) 来使其工作,知道为什么吗?文档说 m.group(0) 是整个模式,实际组从 1 开始,但它在实践中不起作用。使用 m.group(1) 我得到“IndexOutOfBoundsException: No group 1”。此外,parts[1] 包含右括号,因此需要过滤掉非数字,如此处建议stackoverflow.com/questions/4030928/…
  • 在诸如\[(.*?)\] 这样的表达式中,在输入"ab [cd] ef" 上调用find 将在第0 组(整场比赛)中给出"[cd]",在第1 组中给出"cd"(这些东西在组内(...) 即匹配.*? 的部分。
  • 哎呀,你是对的,我在构建正则表达式时忘记添加圆括号,无论哪种方式都适合我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-26
  • 1970-01-01
  • 1970-01-01
  • 2020-06-03
  • 1970-01-01
相关资源
最近更新 更多