C# 超快“邮件合并”类型替换

发布于 2024-08-08 18:14:28 字数 138 浏览 4 评论 0原文

当需要替换位的文档不变时(一种邮件合并场景),我希望获得一些有关执行替换的最快方法的指示。

当然,有很多方法可以使用 string.replace 和 regexp 进行替换,但看起来它们每次寻找匹配时都需要解析输入文档。这就是我试图优化的一点。

I hoping for some pointers on the quickest way to do a replace when the document that needs bits replacing is constant (a sort of mailmerge scenario).

Of course there are lots of ways of doing replaces using string.replace and regexp but it looks like they need to parse the input document each time looking for the match. That's the bit I'm trying to optimise.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

滥情稳全场 2024-08-15 18:14:28

我想说你最好的选择可能是将文档分割成一个数组,每个元素都是前一个替换和下一个替换之间的文本。然后,您只需使用字符串连接将分割数组的内容与每个替换标记交错,而不是替换。

一些伪代码:

doc_array = split(input_doc, "token marker")

for each replace_array in set_of_replace_arrays:
    this_doc = ""

    while elements remain in doc array:
        this_doc.concat(next doc element)

        if any elements remain in replace array:
            this_doc.concat(next replace element)

    output this_doc

I'd say your best bet would probably be to split the document into an array with each element being the text that's in between the previous replacement and the next. Then instead of replacing, you simply interleave the contents of your split array with each of the replacement tokens using string concatenation.

Some pseudocode:

doc_array = split(input_doc, "token marker")

for each replace_array in set_of_replace_arrays:
    this_doc = ""

    while elements remain in doc array:
        this_doc.concat(next doc element)

        if any elements remain in replace array:
            this_doc.concat(next replace element)

    output this_doc
墨离汐 2024-08-15 18:14:28

为了提高灵活性,您可以使用 XslCompiledTransform 并让它输出文本。它针对快速 XML 和文本生成进行了优化,如果需要,您也可以包含一些逻辑。

For increased flexibility, you could use a XslCompiledTransform and have it output text. It's optimized for fast XML and text generation, and you could include some logic too if required.

沒落の蓅哖 2024-08-15 18:14:28

好吧,由于您不想解析并且输入文档是恒定的,因此您可以使用 MemoryStream 来处理原始文档并通过使用其绝对位置来更改位。

另一种方法是使用 String.Format 标记作为占位符:

string input = "Dear {0} {1}";
//...
return String.Format(input, "Mr.", "Farias");

Well, as you don't want to parse and your input document is constant, you could use a MemoryStream to handle your original document and change your bits by using their absolute position.

Another way could be use that String.Format markers as placeholders:

string input = "Dear {0} {1}";
//...
return String.Format(input, "Mr.", "Farias");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文