使用正则表达式查找文本时,我在某处出错。
这是我正在使用的代码。
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
我试图在段落中找到
Event Handling
或Event Handling (EH)
,但是OR运算符不起作用。当我尝试分别找到
Event Handling
时,它可以工作。对于Event Handling (EH)
同样。但是与OR运算符|
一起使用时,它不起作用。为什么? 最佳答案
Word的内置查找功能仅支持有限的一组正则表达式。如果要使用完整,常用的标准正则表达式,则必须执行以下操作:
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
如果您选择段落并运行该段落,则文本将按预期替换。但是请注意,
Event Handling \(EH\)
应该在搜索模式替换"(Event Handling \(EH\)|Event Handling)"
中排在第一位,因为如果Event Handling
如您最初编写的那样排在第一位,它将被替换掉,从而留下所有(EH)
。或者,如果您想使用Word的内置
Find
,则只需进行两次搜索-在这里,Event Handling \(EH\)
应该是第一个:'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