使用正则表达式查找和替换 Word |交替运算符 [英] Word find and replace using regex | alternation operator

查看:18
本文介绍了使用正则表达式查找和替换 Word |交替运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用正则表达式查找文本时,我在某处出错了.

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

我试图在段落中找到 Event HandlingEvent Handling (EH),但 OR 运算符不起作用.

I am trying to find Event Handling or Event Handling (EH) in the passage, but the OR operator is not working.

当我尝试单独查找 Event Handling 时,它可以正常工作.事件处理 (EH) 类似.但是与 OR 运算符 | 一起使用时,它不起作用.为什么?

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 的内置查找功能仅支持有限的一组正则表达式.如果你想使用完整的、常用的、标准的正则表达式,你必须这样做:

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

如果您选择您的段落并运行它,文本将按您的意图替换.但请注意,Event Handling \(EH\) 应该出现在搜索模式交替 "(Event Handling \(EH\)|Event Handling)" 中,因为如果 <代码>事件处理在您最初编写时首先出现,它将首先被替换,留下任何(EH).

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.

或者,如果您想使用 Word 的内置 Find,那么只需进行两次搜索——这里也是,Event Handling \(EH\) 应该是第一个:

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

这篇关于使用正则表达式查找和替换 Word |交替运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆