[英]replacing strings with Regex.Replace()
我相信这很简单,但我错过了一些东西......
我有2个字符串:
String x = "ows__x05de__x05e1__x05e4__x05e8__x00"
String y = "ows__x05de__x05e1__x05e4__x05e8__x000"
字符串之间的差异是字符串y中的附加“0”。
我有一个XML文档,其中有两个字符串多次。 我需要将String x替换为“CustName”,将String y替换为“CustNumber”,但我不能使用.Replace()
方法,因为字符串x和字符串y与此方法相同。 我试过使用Regex.Replace()
:
string XMLdummy = "ows__x05de__x05e1__x05e4__x05e8__x00='custName....' ows__x05de__x05e1__x05e4__x05e8__x000='33346464...'";
Regex rx = new Regex("^ows__x05de__x05e1__x05e4__x05e8__x00{1,36}$");
string result = rx.Replace(XMLdummy, "CustName");
Regex rx2 = new Regex("^ows__x05de__x05e1__x05e4__x05e8__x000{1,37}$");
result = rx2.Replace(XMLdummy, "CustNumber");
System.Diagnostics.Debug.WriteLine(result);
没有任何反应,结果等于XMLdummy原始字符串。
要求的结果应该是:
CustName='custName....' CustNumber='33346464...'
更改替换字符串的顺序,先用更多字符替换字符串,然后再替换另一个字符串:
XMLdummy = XMLdummy.Replace(y, "CustNumber").Replace(x, "CustName");
这样可以防止一次性更换两种类型的字符串,并有效地执行您想要的操作。
为了更好的解释,请考虑两个字符串:
The word is 'GRAY'
和
The word is 'GRAYSCALE'
现在,假设你要替换GRAY
与FirstWord
和GRAYSCALE
与SecondWord
。
如果你先取代GRAY
,你会得到:
The word is 'GRAY' -> The word is 'FirstWord'
The word is 'GRAYSCALE' -> The word is 'FirstWordScale'
另一方面,如果您更改了两个字符串的替换顺序并使用了两个步骤,您将得到正确的结果:
The word is 'GRAY' -> The word is 'GRAY'
The word is 'GRAYSCALE' -> The word is 'SecondWord'
-------------
The word is 'GRAY' -> The word is 'FirstWord'
The word is 'SecondWord' -> The word is 'SecondWord'
是的,你正确使用两个字符串只有在第二个“0”中更多,所以当你要改变时,它将改变两个字符串并在第二个字符串中替换CutomerName第一个字符串和CustomerName0。
我试图重用你的代码并找到你可以使用以下代码使用Regex更改字符串的解决方案,使用下面的代码来执行它。
string XMLdummy = "ows__x05de__x05e1__x05e4__x05e8__x00='custName....'"+
"ows__x05de__x05e1__x05e4__x05e8__x000='33346464...'";
string rx = @"^ows__x05de__x05e1__x05e4__x05e8__x00${0,35}";
XMLdummy = Regex.Replace(XMLdummy, rx, "CustName");
string rx2 = @"ows__x05de__x05e1__x05e4__x05e8__x000";
XMLdummy = Regex.Replace(XMLdummy, rx2, "CustNumber");
System.Diagnostics.Debug.WriteLine(XMLdummy);
输出:“CustName ='custName ....'CustNumber ='33346464 ...'”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.