代码之家  ›  专栏  ›  技术社区  ›  Wei Lin

Regex模式“\{\{*Tag*\}\}”无法替换xml字符串

  •  0
  • Wei Lin  · 技术社区  · 2 年前

    源xml字符串

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

    预料

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

    我尝试使用下面的正则表达式和C#代码来替换,但没有成功。 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

    我想 * 之间 {} 可以替换它,朋友们能给我一些关于我错误的想法吗,真的很感激!

    更新2:

    我试着用 \{\{.+Company_Name.+\}\} 但它在第一个之间得到了完整的字符串 {{ 最后 }} , online demo enter image description here

    2 回复  |  直到 2 年前
        1
  •  1
  •   Slack Groverglow    2 年前

    我想有两个问题。

    1. 您没有匹配“{{”之后的任何字符。它应该是 .* 而不是 *

    2. 我认为你没有匹配多行。您需要指定的匹配项 newline 以及: (.|\n)* 而不是 *

    为您提供正则表达式字符串:

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

    您可能可以使用更简单的正则表达式 \{\{.*CreateDate.*\}\} 通过设置 RegexOptions.Multline

        2
  •  1
  •   Quercus    2 年前

    试试这个: {{[^{}]*CreateDate[^{}]*}}