Find and repalce text (placeholders) between ## using C#

Hello,

I have several placeholders in a documents. All placeholder are formatted like
####. How can by using .net I find all the placeholders using “##” as key in a document and list it. I want to build something to dynamically check that all the required placeholders are in the document.

thanks

Hi Pratyush,

Thanks for your query. Please see the following code snippet to get all placeholders in document. Hope this helps you. It would be great, If you share your document so that we can have exact idea about your question. Let us know, If you have any more queries.

Document doc = new Aspose.Words.Document();

NodeCollection nodes = doc.GetChildNodes(NodeType.StructuredDocumentTag, true);
foreach (StructuredDocumentTag sdt in sdts)
{
    //Your code
}

Hello,

Thanks for the reply. See Attached document. I want to list all placeholder Starting with ## in the document and display on my Asp.NET page

Hi Pratyush,

Thanks for your inquiry. In your case, i will suggest you following code snippet:

Document doc = new Document(“D:/ temp / input.docx”);
Regex regex = new Regex(@"(?%##(.*?)##%)", RegexOptions.IgnoreCase);
doc.Range.Replace(regex, new InsertDocumentAtReplaceHandler(), true);
doc.Save("D:/temp/Out.docx");

public class InsertDocumentAtReplaceHandler : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        String title = e.Match.Groups["title"].Value.Trim();
        //Pass title variable to interpret translator
        e.Replacement =  "ReplaceTitleString";
        return ReplaceAction.Replace;
    }
}

I hope this will help.

Hello,

I tried but above code is just creating the same file with exact same content. Any help?

Thanks
Pratyush Kumar

Hi Pratyush,

Thank you for details. Please change regular expression as following:

Regex regex = new Regex(@"(?##(.*?)##)", RegexOptions.IgnoreCase);

Sorry for inconvenience.

Hello,

Thank you, it worked like Charm !!. Now my issue is I have version 6.5. I can see IReplacingCallback is not available in old version. Do you know of any call which I can use to achieve same functionality?

Thanks
Pratyush

Hi Pratyush,
Thanks for your request. Unfortunately, there is no other way to get list of nodes in match without using IReplacingCallback. But if you just need to find and replace some values, you can use overload that takes a string as the second parameter:
https://docs.aspose.com/words/net/find-and-replace/
Hope this might help you.