Find and replace merge fields with other merge fields

The tags we use for repeating blocks in our Word templates and merge fields that look like rb:start:BlockOne and end with rb:end:BlockOne. If I try to do doc.getMailMerge().setRegionStartTag(“rb:start”), I get an exception “A mail merge region tag can not contain reserved separating characters”. We have 1000s of templates, updating them manually is not feasible.

So, I am trying to do some prep work on the document prior to the merge, to change all the rb:start: mail merge tags to TableStart: and all the rb:end: tags to TableEnd: similar to Preparing document to use Mail Merge except I don’t believe I can make a regex pattern that finds merge fields.

What would be ideal is being able to use setFieldMergingCallback, and in the fieldMerging method do like:
if (field.getFieldName().startsWith(“rb:start:”))
field.setFieldName(“TableStart:” + field.getFieldName().substring(9));

But you cannot do this, there is no “setFieldName” method. As per example I linked, you can create merge fields with DocumentBuilder, but how do I know where to insert them? FieldMergingArgs tells you nothing about where the merge field is located that would enable you to use DocumentBuilder to insert a new merge field where the old merge field was located.

Or maybe I just don’t have the right approach? Many thanks for any suggestions.

@NigelGay If you would like to rename merge fields in your templates, you can use code like the following:

Document doc = new Document("C:\\Temp\\in.docx");

for (Field f : doc.getRange().getFields())
{
    if (f.getType() == FieldType.FIELD_MERGE_FIELD)
    {
        FieldMergeField mf = (FieldMergeField)f;
        if (mf.getFieldName().startsWith("rb:start:"))
            mf.setFieldName("TableStart:" + mf.getFieldName().substring(9));
        if (mf.getFieldName().startsWith("rb:end:"))
            mf.setFieldName("TableEnd:" + mf.getFieldName().substring(7));
    }
}
doc.save("C:\\Temp\\out.docx");

In IFieldMergingCallback you can use DocumentBuilder.moveToField method to move the cursor to the location of the mergefield and then insert the required content.