我有一个像下面这样的字符串;
String textToShow = "Appplication [%ApplicationName%]: started at [%Date%][%Time%]"
在我需要用不同的值之间[%
和之间替换字符串的地方%]
。
我在下面确实喜欢,但是它仅适用于第一个,即“ ApplicationName”。
private String getTextVariableName(String stringToShow) {
if (stringToShow.contains("[%") && stringToShow.contains("%]")) {
String content[] = notificationText.split("%");
return content[1];
}
return null;
}
private String replaceValue(String stringToShow, String dataToReplace) {
return stringToShow.substring(0, stringToShow.indexOf("["))
+ dataToReplace
+ stringToShow.substring(stringToShow.indexOf("]") + 1, stringToShow.length());
}
public String processText(String stringToShow, String appname) {
String variableName = getTextVariableName(stringToShow);
String processedText = "Invalid";
if (variableName != null) {
switch (variableName.toLowerCase()) {
case "applicationname":
processedText = replaceValue(stringToShow, appname);
break;
case "datetime":
LocalDateTime currentDateTime = LocalDateTime.now();
String formattedCurrentDateTime = currentDateTime
.format(DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss"));
processedText = replaceValue(stringToShow,
formattedCurrentDateTime);
break;
case "date":
LocalDate currentDate = LocalDate.now();
String formattedCurrentDate = currentDate
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
processedText = replaceValue(stringToShow,
formattedCurrentDate);
break;
case "time":
LocalTime currentTime = LocalTime.now();
String formattedCurrentTime = currentTime
.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
processedText = replaceValue(notificationText,
formattedCurrentTime);
break;
default:
processedText = "Invalid";
break;
}
}
return processedText;
}
如果有更多类似的部分出现,我如何使它适用于整个字符串而又不将其分开?
有没有更好的方法而不拆分?
注意:我从数据库获取此字符串,因此无法更改该字符串。我只需要替换字符串之间[%
和%]
根据字符串名称的部分即可。例如,如果它是一个日期,则必须用日期替换,依此类推。
在正则表达式API提供了所需的逻辑,你可以用它来有效地置换的一个字符串变量的任意数目,见appendReplacement和appendTail:
public String processText(String stringToShow, String appname) {
Matcher m=Pattern.compile("\\[%(\\w+)%\\]").matcher(stringToShow);
if(!m.find()) return stringToShow;
StringBuffer sb=new StringBuffer();
do {
String replacement;
switch(m.group(1).toLowerCase(Locale.ROOT)) {
case "applicationname":
replacement=appname;
break;
case "datetime":
replacement = LocalDateTime.now().format(
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
break;
case "date":
replacement = LocalDate.now().format(
DateTimeFormatter.ofPattern("yyyy-MM-dd"));
break;
case "time":
replacement = LocalTime.now().format(
DateTimeFormatter.ofPattern("HH:mm:ss"));
break;
default:
replacement = "Invalid";
}
m.appendReplacement(sb, replacement);
} while(m.find());
return m.appendTail(sb).toString();
}
请注意,此API缺少的介绍StringBuilder
,因此我们必须在StringBuffer
此处使用。这在Java 9中已解决。
请注意,如果替换字符串中出现and字符,则为它们appendReplacement
分配特殊的含义。如果您怀疑它们出现在替换字符串中,但想从字面上插入字符串,则可以使用,即。$
\
quoteReplacement
m.appendReplacement(sb, Matcher.quoteReplacement( replacement));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句