Free Support Forum - aspose.com

Find and Replace text between delimiters

Hi,

i’m trying to realize an application that search through a word file some text with delimiters (<> $$xxx$$ for example), and if found replaces it with another text.
I tried to look between the guides and the forum but found nothing. Could you help me?

Thanks
Alberto

Hi Alberto,

Thanks for your request. Sure you can achieve this. You can use IReplacingCallback and regular expressions to achieve this. For instance see the following simple code:

[Test]

public void Test001()

{

// Open document.

Document doc = new Document(@"Test001\in.doc");

// Replace placeholders like <> with values.

doc.Range.Replace(new Regex(@"\<\<(?\S+)\>\>"), new PlaceholderReplacingCallback(), false);

// Save output.

doc.Save(@"Test001\out.doc");

}

private class PlaceholderReplacingCallback : IReplacingCallback

{

public ReplaceAction Replacing(ReplacingArgs args)

{

// Get the name of placeholder (text betwwen delimiters).

string name = args.Match.Groups["name"].Value;

// Set the appropriate replacement.

switch (name)

{

case "FirstName":

args.Replacement = "Alexey";

break;

case "LastName":

args.Replacement = "Noskov";

break;

}

return ReplaceAction.Replace;

}

}

But if what you need is filling your template with data, then I think Mail Merge might be a better option for you. Please follow the link for more information:

http://www.aspose.com/documentation/.net-components/aspose.words-for-.net/simple-mail-merge-explained.html

Best regards,

thanks alexey!

yes mail merge could be the better option, but can i use the mail merge with a document where the user just type, for example, &&FirstName&& ?

Hi

Thanks for your request. No, you cannot. To use mail merge, you should use mergefields as placeholders. However, nothing is impossible. You can use IReplacingCallback to replace placeholders with mergefields. You can find a simple code example here:

http://www.aspose.com/community/forums/266470/merge-field-formatting/showthread.aspx#266470

Best regards,

Thanks for the reply!

Now i’ll try both the solution!