繁体   English   中英

String.replace() 方法不起作用

[英]String.replace() method not working

我正在我公司的一个大项目中工作,在使用 String 的替换方法时遇到了一个奇怪的错误。

这是场景:

我正在使用检索这些属性的单例类从属性文件中获取值。 我有一个 DATA 字符串,其中包括两个替换键,这些键应该用以编程方式生成的值替换。

例如:

String strDetails = PropertyLoader.get("details");
String strDataKey1= PropertyLoader.get("datakey1");
String strDataKey2 = PropertyLoader.get("datakey2");

strDetails = strDetails.replace(strDataKey1, "Programmatically Generated Value 1");

strDetails = strDetails.replace(strDataKey2, "Programmatically Generated Value 2");

在上面的代码替换strDataKey1工作但strDataKey2不是。

我创建了简单的 Java 程序来测试它,它的工作方式与我尝试调试上述两行代码中的代码相同,所有值都按预期出现,但是strDataKey2的替换结果失败。

注 - strKey1strKey2都有特殊字符'$' 请告知是否有人知道如何修复它。 我正在使用 Eclipse 最新版本的 JavaEE 我不能在我公司使用其他 IDE。

可能strDataKey1strDataKey2具有互补值。

例子:

strDataKey1 = "foo";
strDataKey2 = "foobar"; 
strDetails = "foobar foo bar 123 foobar foo";

strDetails = strDetails.replace(strDataKey1, "Value1"); //4 matches
//strDetails is "Value1bar Value1 bar 123 Value1bar Value1"

strDetails = strDetails.replace(strDataKey2, "Value2"); //0 matches
//strDetails is "Value1bar Value1 bar 123 Value1bar Value1"

当您替换strDataKey1“使用”了锚点,然后替换了strDataKey2 ,您没有任何修改。

检查strDataKey1strDataKey2的值,并strDataKey2进行一些考虑,例如用strDataKey2值、转义符或分隔符(如果可以解决问题)将它们包装起来。

当您进行第二次替换时,似乎 strDetails 没有 strDataKey2 。 尝试像下面这样重置,看看它是否有效

String strDetails = PropertyLoader.get("details");
String strDataKey1= PropertyLoader.get("datakey1");
String strDataKey2 = PropertyLoader.get("datakey2");
String strDetailsOrg = strDetails;

strDetails = strDetails.replace(strDataKey1, "Programmatically Generated Value 1");

strDetailsOrg = strDetailsOrg.replace(strDataKey2, "Programmatically Generated Value 2");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM