如何在 VBA 中使用正则表达式替换第 n 次出现?

oll*_*lly 1 regex excel vba

例如,我尝试将“This 9 is 8 a 77 6 test”中第二次出现的数字替换为“hello”。

所以我希望结果是“This 9 is hello a 77 6 test”。

相反,我得到的是“hellohello test”。

我在用着:

=RegexReplace("This 9 is 8 a 77 6 test","(?:\D*(\d+)){2}","hello")
Run Code Online (Sandbox Code Playgroud)

其中 RegexReplace 定义如下:

Function RegexReplace(text As String, pattern As String, replace As String)

        Static re As Object

        If re Is Nothing Then
            Set re = CreateObject("VBScript.RegExp")
            re.Global = True
            re.MultiLine = True
        End If

        re.IgnoreCase = True
        re.pattern = pattern
        RegexReplace = re.replace(text, replace)
        Set re = Nothing

End Function
Run Code Online (Sandbox Code Playgroud)

Wik*_*żew 6

你需要使用

=RegexReplace("This 9 is 8 a 77 6 test","^(\D*\d+\D+)\d+","$1hello")
Run Code Online (Sandbox Code Playgroud)

请参阅正则表达式演示

细节

  • ^- 字符串的开头
  • (\D*\d+\D+)- 第 1 组:零个或多个非数字 + 一个或多个数字 + 一个或多个非数字(该值将使用编号替换反向引用在结果中恢复$1
  • \d+- 一位或多位数字。

要替换第三个数字,您可以将模式重构为^(\D*(?:\d+\D+){2})\d+. 请注意捕获括号和非捕获括号的位置。

  • @olly `^((?:.*?\b\d+){N-1}.*?)-?\d+` 其中 `N` 需要根据您的要求进行调整。这可以进一步简化(“{1}”是多余的,“{0}”没有意义,因为您可以删除整个组)。 (2认同)