c# - Docx - 删除文档的一部分

标签 c# regex novacode-docx

有没有办法删除文档中可以指定开始和结束标签的部分?

我需要一种方法,可以通过传递开始和结束捕获来删除文档的一部分(@@DELETEBEGIN 和 @@DELETEEND)

例如,我的文档中有此内容:

Hello, welcome to this document

@@DELETEBEGIN{Some values to check in the code}

Some text that will be removed if the value is true

@@DELETEEND

Final Line

最佳答案

如果您需要删除从 @@DELETEBEGIN 到 @@DELETEEND 的文本,其中 @@DELETEBEGIN 不在 Paragraph 的开头且 @@DELETEEND 不在 的结尾>段落,这段代码应该可以工作。

DocX document = DocX.Load("C:\\Users\\phil\\Desktop\\text.docx");
bool flag = false;
List<List<string>> list1 = new List<List<string>>();
List<string> list2 = new List<string>();
foreach (Novacode.Paragraph item in document.Paragraphs)
{
    //use this if you need whole text of a paragraph
    string paraText = item.Text;
    var result = paraText.Split(' ');
    int count = 0;
    list2 = new List<string>();
    //use this if you need word by word
    foreach (var data in result)
    {
        string word = data.ToString();
        if (word.Contains("@@DELETEBEGIN")) flag = true;
        if (word.Contains("@@DELETEEND"))
        { 
            flag = false;
            list2.Add(word);
        }
        if (flag) list2.Add(word); 
        count++;
    }
    list1.Add(list2);
}
for (int i = 0; i < list1.Count(); i++)
{
    string temp = "";
    for (int y = 0; y < list1[i].Count(); y++)
    {
        if (y == 0) 
        {
            temp = list1[i][y];
            continue;
        }
        temp += " " + list1[i][y];                   
    }
    if (!temp.Equals("")) document.ReplaceText(temp, "");
}
document.Save();

我必须对此给予一些信任post用于循环遍历每个单词。

关于c# - Docx - 删除文档的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32122412/

相关文章:

c# - 对一个字符串使用多个字符串生成器

c# - 从 .NET Core 注销 IdentityServer4 让我重新登录

c# - 如何使用 Novacode DocX 在现有表中添加新行

novacode-docx - Novacode DocX 同一文档中的不同页面方向

merge - Novacode Docx MergeCells 段落删除

c# - 将 VSIX 功能添加到 C# 类库

c# - C#中的UDP套接字?

用于匹配字符串部分不相同的正则表达式

正则表达式允许以逗号分隔的代码列表

python - 正则表达式命名组(如果存在)