I have a function which uses a regular expression to search through the document text, which needs to make changes to the found text based on their position in the document.
This works fine, except when there's a field code in the document, the positions of the found text is not correct, and I can't figure out what is offsetting the position (I tried checking the length of the field.result vs the field.code, but the amount of offset doesn't match any combination of these lengths)
Here is a boiled down version of the code I am using.
Code:
Set re = New RegExp
re.Pattern = "(TEXT1)( Text2)? \(text3\)( text4)?(?: text5)?"
re.IgnoreCase = True
re.Global = True
txt = ActiveDocument.range.Text
If re.TEST(txt) Then
'get all matches
Set allmatches = re.Execute(txt)
'look at each match and hilight corresponding range
For Each m In allmatches
' Set new Range
startPos = m.FirstIndex
endPos = startPos + m.Length
Set newRNG = ActiveDocument.Range(start:=startPos, End:=endPos)
' This range is NOT correct if there are fields
newRNG.Select
' Code here to process found text
if (condition) then
' Edit range here
end if
Next m
End If
This code works fine in the document, it runs through and selects each range found that matches the pattern. But if there is a field in the document (e.g. 'CreateDate' field, or a text field), after it the ranges selected is not the found text, it selects a range before the found text.
Is there a proper way to do the regular expression search that will allow me to edit the found ranges when necessary? I don't believe I can use a word 'find' using wildcards, since I need to use the SubMatch values (left out here for brevity), not the full found text, and I don't think wildcards would perform the search I need to use.
I hope I have explained my issue correctly, please let me know if there is any more information I need to provide.