Spire.Doc is a professional Word .NET library specifically designed for developers to create, read, write, convert and print Word document files. Get free and professional technical support for Spire.Doc for .NET, Java, Android, C++, Python.

Tue Jan 03, 2023 10:09 pm

I have the code that searches the document and using regex retrieves a list of text selections based on a tag that I'm looking for. Once I loop through the selections and find the appropriate selection, how can I replace the tag only within that specific text selection? If I do a generic doc.replace or even a paragraph.replace it could replace more tags than I want. I only want to do a replace within a specific text selection that I have found. Is there a way to do that?

garciag
 
Posts: 2
Joined: Fri Mar 08, 2019 4:56 pm

Wed Jan 04, 2023 10:09 am

Hi,

Thanks for your inquiry.
After getting the TextSelection[], you can loop through it and get the TextRange’s detailed information, such as the index of its located paragraph, then you can replace the text in some specific paragraphs. You can see my code for reference.
Code: Select all
            //key:index of paragraph
            Dictionary<int, TextRange[]> dic = new Dictionary<int, TextRange[]>();
            Document doc = new Document();
            doc.LoadFromFile("sample.docx");
           
           
            Regex regex = new Regex("\\#\\w+\\b");
            // find the text
            TextSelection[] selections = doc.FindAllPattern(regex);
           
            int index = 0;
            int lastParagraphIndex = 0;
           
            foreach (TextSelection selection in selections)
            {
                TextRange range = selection.GetAsOneRange();
               
                // get range's owner paragraph
                Paragraph paragraph = range.OwnerParagraph;

                // get the paragraph's owner body
                DocumentObject documentObject = paragraph.Owner;
                //get the body's owner section
                Section section = (Section)documentObject.Owner;

                // get the index of specific paragraph
                int paragraphIndex  = section.Paragraphs.IndexOf(paragraph);
               
                if(paragraphIndex != lastParagraphIndex){
                    index = 0;
                }
                if (dic.ContainsKey(paragraphIndex))
                {
                    dic[paragraphIndex][index++] = range;
                   
                }
                else
                {
                    TextRange[] tra = new TextRange[selections.Length];
                    tra[index++] = range;
                    dic[paragraphIndex] = tra;

                }
                lastParagraphIndex = paragraphIndex;

            }

            // for example, replace the second paragrraph's second textrange.
            int replaceParaIndx = 1;
            int replaceTRIndex  = 1;
            string replaceText = "spire";
            foreach (int i in dic.Keys)
            {
                if (i == replaceParaIndx)
                {

                    TextRange tr = dic[i][replaceTRIndex];
                    tr.Text = replaceText;

                }
            }
            doc.SaveToFile("output.docx", FileFormat.Docx);

If the code does not meet your requirement, could you please provide us with the following messages? You can send them to us via email ([email protected]) or attach them here. Thanks for your assistance.
1) some sample files.
2) the effect you want to achieve.

Sincerely,
Triste
E-iceblue support team
Last edited by Triste.Dai on Thu Jan 05, 2023 8:50 am, edited 1 time in total.
User avatar

Triste.Dai
 
Posts: 1000
Joined: Tue Nov 15, 2022 3:59 am

Wed Jan 04, 2023 4:20 pm

Thank you, however that's not exactly what I'm looking for. Essentially I have several paragraphs that are enclosed with tags. Such as:
<tag>This is a sample text</tag> some more text in between <tag> this is more text</tag>.

After using the FindAllPattern with a regex pattern I get both selections as a TextSelection:
1: <tag>This is a sample text</tag>
2: <tag> this is more text</tag>

While looping through the TextSelection's I decide that I want to remove selection 1 and keep selection 2. It's easy to remove selection 1 by replacing it with an empty string. However for TextSelection 2 I want to keep the text (With any formatting it might already have) but remove the <tag> and the </tag>. I can remove the tags by processing the text using the .SelectedText method and replacing the text but that doesn't preserve any formatting of the remaining text.

I wanted to do a replace on the TextSelection to remove the tags and keep the text with all the formatting. Hope that makes sense.

garciag
 
Posts: 2
Joined: Fri Mar 08, 2019 4:56 pm

Fri Jan 06, 2023 5:47 am

Hi,

Thanks for your feedback.
You can see the following code for reference,
Code: Select all
            Document doc = new Document();
            doc.LoadFromFile("test.docx");
           
            Regex regex = new Regex("<tag>([\\s\\S]*?)</tag>");
            // find the text
            TextSelection[] selections = doc.FindAllPattern(regex);
            // for example,remove the first selection.
            selections[0].GetAsOneRange().Text = "";
            string text;
            foreach (TextSelection selection in selections)
            {
               
                TextRange[] ranges = selection.GetRanges();
                foreach (TextRange range in ranges)
                {
                    if (range.Text.Contains("<tag>"))
                    {
                        text = range.Text.Replace("<tag>","");
                        range.Text = text;
                    }

                    if (range.Text.Contains("</tag>"))
                    {
                        text = range.Text.Replace("</tag>", "");
                        range.Text = text;
                    }
                }
            }
            doc.SaveToFile("output.docx", FileFormat.Docx);

the input file and output file are attached. If there are any further questions, please feel free to contact us.

Sincerely,
Triste
E-iceblue support team.
User avatar

Triste.Dai
 
Posts: 1000
Joined: Tue Nov 15, 2022 3:59 am

Return to Spire.Doc