regex - 如何在word中使用VBA(宏)使用/启用(RegExp对象)正则表达式

标签 regex vba visual-studio-macros

我进行了大量的谷歌搜索,以获得有关如何在 VBA 中使用或开始使用正则表达式的正确答案。

终于明白了,所以我想与大家分享我的知识。如果我错了,请纠正我。

最佳答案

默认情况下,Word 2007 中禁用正则表达式选项,要启用该选项,请执行以下步骤,

1).转到“工具”>“引用”,如下所示。 enter image description here

2).现在勾选“Microsoft VBScript Regular Expressions 5.5”选项,然后按 oh,如下所示。 enter image description here

3).现在您可以在 VBA 脚本中创建 RegExp 对象。您可以验证它是否在对象数据库中搜索,如下所述。 查看>对象浏览器(或按F2),如下所示。

enter image description here

并搜索 RegExp 对象

enter image description here

4). RegExp 对象使用正则表达式来匹配模式。以下属性由 RegExp 提供。这些属性设置模式以比较传递给 RegExp 实例的字符串:

a. 模式:定义正则表达式的字符串。

b. IgnoreCase:一个 bool 属性,指示是否必须针对字符串中所有可能的匹配项测试正则表达式。

c. 全局: 设置一个 bool 值或返回一个 bool 值,指示模式是否必须匹配整体中的所有出现情况搜索字符串,或者模式是否必须仅匹配第一次出现的情况。

RegExp提供了以下方法来确定字符串是否与正则表达式的特定模式匹配:

d. 测试:返回一个 bool 值,指示正则表达式是否可以成功匹配字符串。

e. 执行:返回一个 MatchCollection 对象,其中包含每个成功匹配的 Match 对象。

请在 Microsoft msdn 论坛中查找提供的 RexExp 类似示例。

Function TestRegExp(myPattern As String, myString As String)
   'Create objects.
   Dim objRegExp As RegExp
   Dim objMatch As Match
   Dim colMatches   As MatchCollection
   Dim RetStr As String

   ' Create a regular expression object.
   Set objRegExp = New RegExp

   'Set the pattern by using the Pattern property.
   objRegExp.Pattern = myPattern

   ' Set Case Insensitivity.
   objRegExp.IgnoreCase = True

   'Set global applicability.
   objRegExp.Global = True

   'Test whether the String can be compared.
   If (objRegExp.Test(myString) = True) Then

   'Get the matches.
    Set colMatches = objRegExp.Execute(myString)   ' Execute search.

    For Each objMatch In colMatches   ' Iterate Matches collection.
      RetStr = RetStr & "Match found at position "
      RetStr = RetStr & objMatch.FirstIndex & ". Match Value is '"
      RetStr = RetStr & objMatch.Value & "'." & vbCrLf
    Next
   Else
    RetStr = "String Matching Failed"
   End If
   TestRegExp = RetStr
End Function

我希望它可以对某些人有所帮助,因为我在上面浪费了几乎半天的时间。

谢谢

关于regex - 如何在word中使用VBA(宏)使用/启用(RegExp对象)正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25102372/

相关文章:

c - 宏的 "incomplete type not allowed"错误?

excel - 优化问题。查询不适用于超过 5 个股票代码。每次我用 5 个股票运行它平均需要 5-6 分钟

c++ - 修复 C++ 中的宏重新定义

java - 替换 token 中的所有内容,字母字符和句点除外

javascript - 正则表达式替换字符串中的函数

vba - 将背景图像添加到特定单元格

excel - 看似非常简单的 Excel 无响应问题

c# - 如何获取 Visual Studio 2008 编辑器窗口的左上角屏幕位置?

python glob 为 "excluding pattern"

javascript - 在javascript中替换url中的查询字符串