我正在尝试使用默认数值替换两个xml标记之间的值。
在以下字符串中,我需要将DOB的值替换为1900-01-01。
输入:
<FirstName>TEST</FirstName>
<DOB>TEST</DOB>
<tt:LastName>TEST</tt:LastName>
<tt:DOB>TEST</tt:DOB>
期望的输出:
<FirstName>TEST</FirstName>
<DOB>1900-01-01</DOB>
<tt:LastName>TEST</tt:LastName>
<tt:DOB>1900-01-01</tt:DOB>
这就是我目前所拥有的:
string pattern = @"<((DOB|tt:DOB).*>).*?</\1";
string input = "<FirstName>TEST</FirstName><DOB>TEST</DOB><tt:LastName>TEST</tt:LastName><tt:DOB>TEST</tt:DOB>";
string replacement = "<$1 1900-01-01 </$1";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
这给了我:
<DOB> 1900-01-01 </DOB>
<tt:DOB> 1900-01-01 </tt:DOB>
我能够设置默认日期,但不能在替换变量中的值和第一个子模式之间放置空格。如果我取出空格,它会读到&#34; 1900&#34;作为第一个子模式的一部分。
以下是我的正则表达式测试的链接:https://regex101.com/r/fK3yA5/6
有没有办法在不使用空格或引号的情况下用数字替换值?
答案 0 :(得分:2)
Jon Skeet is probably correct, you should use the XElement API. However, to answer your question, you can do it as follows by changing the Replacement regex to this:
string replacement = "<${1}1900-01-01 </$1";
Notice how $1
became ${1}
. See here for more details