James
James

Reputation: 157

Replacing value in XML tags in C# using Regex

I am trying to replace a value between two xml tags with a default numeric value.

In the following string, I need to replace the value of DOB w/ 1900-01-01.

Input:

<FirstName>TEST</FirstName>
<DOB>TEST</DOB>
<tt:LastName>TEST</tt:LastName>
<tt:DOB>TEST</tt:DOB>

Desired Output:

<FirstName>TEST</FirstName>
<DOB>1900-01-01</DOB>
<tt:LastName>TEST</tt:LastName>
<tt:DOB>1900-01-01</tt:DOB>

This is what I currently have:

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);

Which gives me:

<DOB> 1900-01-01 </DOB>
<tt:DOB> 1900-01-01 </tt:DOB>

I'm able to set the default date, but not without putting a space between the value and the 1st subpattern in the replacement variable. If I take out the spaces, it reads "1900" as part of the first subpattern.

enter image description here

Here is a link to my regex test: https://regex101.com/r/fK3yA5/6

Is there any way to replace the values with a number without using a space or quotes?

Upvotes: 0

Views: 1327

Answers (1)

Shlomo
Shlomo

Reputation: 14370

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

Upvotes: 2

Related Questions