0

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?

3
  • Why would you want to use regular expressions for this instead of an XML API? Commented Jul 13, 2015 at 20:30
  • Hi Jon, I'm still very new to programming in general, so I'm not aware of all the tools in C#. The file that I'm editing isn't an xml data type but a nvarchar(max). It does contain xml tags throughout the file though. Would an XML API be able to edit my file even though its not an xml data type? If so, whats the name of this api? thanks! Commented Jul 13, 2015 at 20:42
  • Is it genuinely an XML document? If so, load it into an XML API, and manipulate everything that way. It'll be much less painful than using regular expressions. Read a tutorial for "LINQ to XML". Commented Jul 13, 2015 at 20:44

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.