0

I'm using DocX library to replace text inside word document. I want to somehow find all strings between "[]" inside my template docx file, for example [Name], [LastName], [Date] etc... and replace it with values which I previously load to datagridview which have same column name(Name, LastName, Date). Here is what I have so far:

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);
    }
}
Vadim Martynov
  • 8,602
  • 5
  • 31
  • 43
dilesko
  • 21
  • 7

2 Answers2

0

Try changing your regular expression, it looks like this question here is basically doing the same thing you are trying to (with regards to finding the values between two characters).

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

If you use that premise then iterate through all matches. I suspect you will be able to alter your code to do what you are trying to achieve.

Community
  • 1
  • 1
Pheonyx
  • 851
  • 6
  • 15
0

Here is your problem:

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

See your RegEx here

You are matching any of the characters you have put between the brackets [], meaning your RegEx will only match the characters ., * and ? literally.

What you need to do is to escape these brackets:

\[.*?\]

See it working here

Alexander Ortiz
  • 529
  • 7
  • 14