Hi all,
I’m seeing what I think (according to how I read the documentation) an inconsistent behavior when using a Regex expression as part of Range.Replace when the IReplacingCallback is implemented.
See below for example code which also has in the comments what is happening.
Public Sub test(iDocument As Document)
'The document has 2 ocurrences of the @Table_Start@ strings and all processing works as expected
Dim regex_start As New Regex("@Table_Start@", RegexOptions.IgnoreCase)
Dim obj_start As New FindNode()
Dim startPara As Paragraph = Nothing
Dim startParaArray As New ArrayList
iDocument.Range.Replace(regex_start, obj_start, False)
For Each node As Node In obj_start.nodes
startPara = DirectCast(node.ParentNode, Paragraph)
startParaArray.Add(startPara)
Next
'<>
'This works fine
If startParaArray.Count > 0 Then
iDocument.Range.Replace(regex_start, "")
End If
'The document also has multiple occurrences of a pattern that will match the regex below.
'Despite there being 2 ocurrences of @ref_para1@ and several others that match @ref_*@, only 1 ocurrence of @ref_para1@ is found*
Dim regex_ref As New Regex("@ref_(.)@", RegexOptions.IgnoreCase)
Dim obj_ref As New FindNode()
Dim refPara As Paragraph = Nothing
Dim refParaArray As New ArrayList
iDocument.Range.Replace(regex_ref, obj_ref, False)
For Each node As Node In obj_ref.nodes
refPara = DirectCast(node.ParentNode, Paragraph)
refParaArray.Add(refPara)
Next
'<>
'And this throws an exception "The match includes one or more special or break characters and cannot be replaced."
If refParaArray.Count > 0 Then
iDocument.Range.Replace(regex_ref, "")
End If
End Sub
Public Class FindNode
Implements IReplacingCallback
'Store Matched nodes in array list
Public nodes As New ArrayList()
Private Function IReplacingCallback_Replacing(e As ReplacingArgs) As ReplaceAction Implements IReplacingCallback.Replacing
Dim currentNode As Node = e.MatchNode
nodes.Add(currentNode)
'Signal to the replace engine to do nothing because we have already done all what we wanted.
Return ReplaceAction.Skip
End Function
End Class