Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Word find and replace using regex | alternation operator

Tags:

regex

ms-word

vba

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?

like image 350
user123 Avatar asked Feb 11 '23 14:02

user123


2 Answers

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
like image 99
Jean-François Corbett Avatar answered Feb 20 '23 21:02

Jean-François Corbett


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

like image 32
OldGit Avatar answered Feb 20 '23 19:02

OldGit