Searching for text strings and replacing them with bookmarks

Hi,

I'd like to be able to take a document, find all instances of a piece of text that is blue and begins with the letter v and replace it with a bookmark of the same name but with a number beforehand. The reason for this is that I have several thousand documents which have unofficial bookmarks where a previous solution simply used Find and Replace. If I can automate the changeover to use bookmarks it will be a lot more efficient.

By the way, the reason for the incremental number is that there may be more than one instance of the "unofficial bookmark" i.e. blue text beginning with the letter v in place.

I've gone through the documentation and cant see anything that indicates this is possible so can anyone help?

Look forward to hearing from you.

John

I’d just add, the previous solution I mentioned (VBA) does something similar by iterating through Document.Words and then using Document.Bookmarks.Add().

Please attach the sample documents here, demonstrating what you initially have and what you want to get as a result. I will then try to compose a working code example for you and post it here.

Hi,

Attached is a very basic example document. It should be fairly self explanatory by the text inside it.

Thanks

John

Please try the following code. It seems to work fine in my test.

public void TestReplaceTextWithBookmarks()

{

Document doc = new Document("BookmarkExample.doc");

doc.Range.Replace(new Regex(@"\bv\w+"), new ReplaceEvaluator(ReplaceEvaluator1), false);

doc.Save("BookmarkExample Out.doc");

}

private int bookmarkCounter = 1;

private ReplaceAction ReplaceEvaluator1(object sender, ReplaceEvaluatorArgs e)

{

Run run = (Run)e.MatchNode;

if (run.Font.Color == Color.FromArgb(0x4F, 0x81, 0xBD))

{

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

builder.MoveTo(e.MatchNode);

string bookmarkName = string.Format("{0}_{1}", bookmarkCounter, e.Match.Value);

builder.StartBookmark(bookmarkName);

builder.Write(e.Match.Value);

builder.EndBookmark(bookmarkName);

bookmarkCounter++;

}

e.Replacement = "";

return ReplaceAction.Replace;

}

Regards,

Hi,

Just tested it and it works a treat. Thank you very much.

John