Java 替换字符串中的变量
我有一个字符串,它包含以下内容Java 替换字符串中的变量,java,string,Java,String,我有一个字符串,它包含以下内容 String msg = "The variables &CHAG_EF and &CHAG_DNE_DTE can be embedded" String test1 = "22/10/2010 00:10:12" String test2 = "25/10/2010 00:01:12" 我需要在字符串变量msg中搜索字符串“&CHAG\u EF”,如果它存在,则替换为test1的值,还需要在字符串变量msg中搜索字符串“&CHAG\u
String msg = "The variables &CHAG_EF and &CHAG_DNE_DTE can be embedded"
String test1 = "22/10/2010 00:10:12"
String test2 = "25/10/2010 00:01:12"
我需要在字符串变量msg中搜索字符串“&CHAG\u EF”
,如果它存在,则替换为test1
的值,还需要在字符串变量msg中搜索字符串“&CHAG\u DNE\u DTE”
,如果它存在,则替换为test2
的值
我怎样才能替换它们呢?太简单了
String msg2 = msg.replace("&CHAG_EF", test1).replace("&CHAG_DNE_DTE", test2);
Java中的字符串是不可变的,因此任何“操纵”方法都会返回新字符串,而不是修改现有字符串。这样做的一个好处是,您可以在许多情况下连锁运营,例如:
String result = msg.replace("&CHAG_EF", test1)
.replace("&CHAG_DNE_DTE", test2);
public static String replaceAll(String text, Map<String, String> params) {
Pattern p = Pattern.compile("&(\\w+)");
Matcher m = p.matcher(text);
boolean result = m.find();
if (result) {
StringBuffer sb = new StringBuffer();
do {
String replacement = params.get(m.group(1));
if (replacement == null) {
replacement = m.group();
}
m.appendReplacement(sb, replacement);
result = m.find();
} while (result);
m.appendTail(sb);
return sb.toString();
}
return text;
}
首先,字符串不能在Java中修改,所以您需要创建具有正确修改值的新版本。有两种方法可以解决此问题:
Map
中,则替换它们。这很类似于String result = msg.replace("&CHAG_EF", test1)
.replace("&CHAG_DNE_DTE", test2);
public static String replaceAll(String text, Map<String, String> params) {
Pattern p = Pattern.compile("&(\\w+)");
Matcher m = p.matcher(text);
boolean result = m.find();
if (result) {
StringBuffer sb = new StringBuffer();
do {
String replacement = params.get(m.group(1));
if (replacement == null) {
replacement = m.group();
}
m.appendReplacement(sb, replacement);
result = m.find();
} while (result);
m.appendTail(sb);
return sb.toString();
}
return text;
}
publicstaticstringreplaceall(字符串文本、映射参数){
模式p=模式编译(&(\\w+);
匹配器m=p.Matcher(文本);
布尔结果=m.find();
如果(结果){
StringBuffer sb=新的StringBuffer();
做{
字符串替换=参数get(m.group(1));
如果(替换==null){
替换=m.组();
}
m、 替换(sb,替换);
结果=m.find();
}而(结果);
m、 (某人);
使某人返回字符串();
}
返回文本;
}