gpt4 book ai didi

java - 替换字符串中的变量占位符

转载 作者:行者123 更新时间:2023-12-04 05:48:15 26 4
gpt4 key购买 nike

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

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

最佳答案

您应该使用 StringBuffer Matcher.appendReplacement Matcher.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.

关于java - 替换字符串中的变量占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10412339/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com