例如,我尝试将“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)
你需要使用
=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+. 请注意捕获括号和非捕获括号的位置。