While using regex for finding text, I am going wrong somewhere.
This is the code I am using.
findText = "(Event Handling|Event Handling \(EH\))"
Debug.Print findText
With Selection.Find
.Text = findText
.Replacement.Text = "Replaced"
.Forward = True
.Wrap = wdFindAsk
.Format = False
.matchCase = False
.MatchWholeWord = False
.MatchWildcards = True
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.Find.Execute Replace:=wdReplaceAll
I am trying to find Event Handling
or Event Handling (EH)
in the passage, but the OR operator is not working.
When I try to find Event Handling
separately, its working. similarly for Event Handling (EH)
. But on together with the OR operator |
it's not working. Why?
Word's built-in Find functionality only supports a limited set of regular expressions. If you want to use the full, usual, standard regular expressions, you have to do something like this:
Dim regExp As Object
Set regExp = CreateObject("vbscript.regexp")
With regExp
.Pattern = "(Event Handling \(EH\)|Event Handling)"
.Global = True
Selection.Text = .Replace(Selection.Text, "Replaced")
End With
If you select your passage and run this, text will be replaced as you intended. But note that Event Handling \(EH\)
should come first in the search pattern alternation "(Event Handling \(EH\)|Event Handling)"
, because if Event Handling
comes first as you originally wrote it, it will get replaced first, leaving any (EH)
behind.
Or, if you want to use Word's built-in Find
, then just do two searches — and here too, Event Handling \(EH\)
should be the first one:
'Settings
With Selection.Find
.Replacement.text = "Replaced"
.Forward = True
.Wrap = wdFindAsk
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = True
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
'First find
With Selection.Find
.text = "Event Handling \(EH\)"
.Execute Replace:=wdReplaceAll
End With
'Second find
With Selection.Find
.text = "Event Handling"
.Execute Replace:=wdReplaceAll
End With
Microsoft Word's Find & Replace does work with Regular Expressions of sorts, but only with a limited set of features. You need to click the Use Wildcards option in the "Advanced"/"More" dropdown pane.
This MVP article documents how to use this: Finding and replacing characters using wildcards
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With