Free Support Forum - aspose.com

Search and replace text with line breaks

Hi there,

I am trying to search for a string and replace it with 3 paragraphs of text. I've read on the forums that it is not possible to search and replace text with special characters. Is there an easy way to do it? Or do I need to search for the tag and insert 3 paragraphs seperately?

John

This task can be solved by doing replace with evaluator. The technique is briefly described in the following article:

http://www.aspose.com/Wiki/default.aspx/Aspose.Words/WorkingWithRange.html

Here is a sample code:

private void ReplaceWithSeveralParagraphs(Document doc)

{

doc.Range.Replace(new Regex("Hello"), new ReplaceEvaluator(MyEvaluator), false);

}

private ReplaceAction MyEvaluator(object sender, ReplaceEvaluatorArgs e)

{

DocumentBuilder builder = new DocumentBuilder(e.MatchNode.Document);

builder.MoveTo(e.MatchNode);

builder.Writeln("Text of paragraph 1.");

builder.Writeln("Text of paragraph 2.");

builder.Writeln("Text of paragraph 3.");

e.Replacement = "";

return ReplaceAction.Replace;

}

Hope you find it helpful.

Best regards,

Hello there,

Thanks for the code. Works great!

I have a question tho...the code above finds the first occurence and writes in the lines. How would I find all occurences and replace them all with the same lines?

I'm speculating I have to make a loop and put builder.MoveTo(e.MatchNode); for all occurence, but how would I know how many occurences r there?

The code given above is meant to find and replace all occurences in the document. I have tested it on several test files. If it replaces only first occurence then please attach a sample document - I will check what can be done.

Best regards,

We are trying to replace the special characters within the range for ex. "Hello\rWorld". Using the mentioned code snippet it does go into my ReplaceEvaluator function. Is this possible?

Hi<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your inquiry. Unfortunately you can’t use special characters in a captured or replacement string. An exception is thrown if a captured or replacement string contain one or more special characters: paragraph break, cell break, section break, field start, field separator, field end, inline picture, drawing object, footnote.

Best regards.