Raj*_*ami 2 java string java-8
我有一个像下面的字符串;
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;
}
Run Code Online (Sandbox Code Playgroud)
如果有更多与此类似的部分出现,我怎样才能使它对整个字符串起作用而不进一步分裂呢?
有没有分裂的更好的方法?
注意:我从DataBase获取此字符串,因此我无法更改字符串.我只需要更换的部分[%
,并%]
根据字符串的名称.就像,如果它是一个日期,它必须被日期替换,依此类推.
关于什么:
String textToShow = "Appplication [%ApplicationName%]: started at [%Date%][%Time%]"
textToShow = textToShow.replace("[%ApplicationName%]","your new string here");
textToShow = textToShow.replace("[%Date%]","your new date here");
textToShow = textToShow.replace("[%Time%]","your new time here");
Run Code Online (Sandbox Code Playgroud)
更直接,更容易,更少错误修剪