user123
user123

Reputation: 43

Word find and replace using regex | alternation operator

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?

Upvotes: 4

Views: 14288

Answers (2)

OldGit
OldGit

Reputation: 11

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

Upvotes: 1

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

Upvotes: 8

Related Questions