0

source xml string

                <w:tc>
                    <w:tcPr>
                        <w:tcW w:w="1870" w:type="dxa"/>
                    </w:tcPr>
                    <w:p w14:paraId="4A2404F3" w14:textId="6CC57F74" w:rsidR="00B721B4" w:rsidRDefault="00B721B4">
                        <w:r>
                            <w:t>{{</w:t>
                        </w:r>
                        <w:proofErr w:type="spellStart"/>
                        <w:r>
                            <w:t>CreateDate</w:t>
                        </w:r>
                        <w:proofErr w:type="spellEnd"/>
                        <w:r>
                            <w:t>}}</w:t>
                        </w:r>
                    </w:p>
                </w:tc>

expect

<w:r>
    <w:t>2022-09-20</w:t>
</w:r>

I tried to use below regex and C# code to replace but it did not work.online demo

void Main()
{
    var input = @"<w:r>
    <w:t>{{</w:t>
</w:r>
<w:proofErr w:type=""spellStart""/>
<w:r>
    <w:t>CreateDate</w:t>
</w:r>
<w:proofErr w:type=""spellEnd""/>
<w:r>
    <w:t>}}</w:t>
</w:r>";
    var pattern = @"\{\{*CreateDate*\}\}";
    var output = Regex.Replace(input,pattern,"2022-09-20");
    Console.WriteLine(output);
}

enter image description here

I think * between {} can replace it, could friends give me idea about my mistakes, really appreciate!

Update2:

I tried to use \{\{.+Company_Name.+\}\} but it get full string between first {{ and last }}, online demo enter image description here

4
  • 3
    Why are you using regex for this when XSLT and XPath are the more applicable solutions? Commented Sep 12, 2022 at 6:05
  • @TanveerBadar I'm trying create a xml template tool, it use string pattern like vue {{tag}} Commented Sep 12, 2022 at 6:09
  • Before writing it in C#, check it manually online on sites like regex101.com Commented Sep 12, 2022 at 6:10
  • 1
    Required reading stackoverflow.com/a/1732454/14868997. Do not use Regex for XML parsing, use a proper XML parser. Commented Sep 12, 2022 at 11:11

2 Answers 2

1

My guess is there are two issues.

  1. You aren't matching "any character after {{". It should be .* instead of just *

  2. I think you aren't matching multi-line. You'll need specify the match for newline as well: (.|\n)* instead of .*

Giving you the regex string:

\{\{(.|\n)*CreateDate(.|\n)*\}\}

You might be able to use a simpler regex \{\{.*CreateDate.*\}\} by setting RegexOptions.Multline

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

Comments

1

Try this one: {{[^{}]*CreateDate[^{}]*}}

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.