【问题标题】:C# find all strings between two characters inside word documentC#查找word文档中两个字符之间的所有字符串
【发布时间】:2016-07-25 05:33:18
【问题描述】:

我正在使用 DocX 库来替换 word 文档中的文本。我想以某种方式在我的模板 docx 文件中找到“[]”之间的所有字符串,例如 [Name]、[LastName]、[Date] 等......并将其替换为我之前加载到具有相同列的 datagridview 的值姓名(姓名、姓氏、日期)。这是我目前所拥有的:

foreach (DataGridViewRow dataGridViewRow in list)
{
    try
    {
        string template = txtUcitajTemplate.Text;
        string text2 = "Aneksi";
        if (!System.IO.Directory.Exists(text2))
        {
            System.IO.Directory.CreateDirectory(text2);
        }
        string path = string.Format("{0}.docx", dataGridViewRow.Cells["Name"].Value.ToString());
        string path2 = System.IO.Path.Combine(text2, path);

        using (DocX document = DocX.Load(template))
        {
            string patternstart = Regex.Escape("[");
            string patternend = Regex.Escape("]");
            string regexexpr = patternstart + @"(.*?)" + patternend;
            // document.ReplaceText(regexexpr, dataGridViewRow.Cells[0].Value.ToString());
            // document.ReplaceText(regexexpr, dataGridViewRow.Cells[1].Value.ToString());
            var regex = new regex("[.*?]");
            var matches = regex.matches(input); //your matches: name, name@gmail.com
            foreach (var match in matches) // e.g. you can loop through your matches like this
            {
                document.ReplaceText(match.ToString(), dataGridViewRow.Cells["Name"].Value.ToString());
                document.ReplaceText(match.ToString(), dataGridViewRow.Cells["LastName"].Value.ToString());
            }
            document.SaveAs(path2);                     
        }
    }
    catch (System.Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

【问题讨论】:

  • 问题是什么?有什么错误吗?问题?出乎意料的结果?
  • 对不起,我不确定我应该在 regex.matches(input) 中输入什么,以搜索孔文档并在 [] 之间找到所有字符串

标签: c# search replace find docx


【解决方案1】:

尝试更改您的正则表达式,看起来这里的这个问题基本上与您尝试做的事情相同(关于查找两个字符之间的值)。

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

如果您使用该前提,则遍历所有匹配项。我怀疑您将能够更改您的代码以实现您想要实现的目标。

【讨论】:

  • 在 Regex.Matches(input) 中我的搜索输入应该是什么?
【解决方案2】:

这是你的问题:

var regex = new regex("[.*?]");

See your RegEx here

您正在匹配放在括号 [] 之间的任何字符,这意味着您的 RegEx 只会匹配字符 .*?

你需要做的是转义这些括号:

\[.*?\]

See it working here

【讨论】:

    猜你喜欢
    • 2021-05-07
    • 1970-01-01
    • 2020-06-03
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多