gpt4 book ai didi

regex - 使用正则表达式查找和替换字符串中模式的所有实例

转载 作者:行者123 更新时间:2023-12-02 08:12:45 24 4
gpt4 key购买 nike

使用 Excel VBA,我试图替换一个简单模式的所有实例,如下所示:

{some text}

与其他一些常量字符串。所以我想找到用大括号括起来的所有文本,并用另一个字符串替换 is(用大括号)。

我使用以下代码:
Dim regEx As Object
Set regEx = CreateObject("VBScript.RegExp")
regEx.Pattern = "\{.*?\}"
qtext = regEx.Replace(qtext, html_input)

在哪里 qtexthtml_input是一些字符串。但这仅替换了该模式的第一个实例。

例如:
qtext = "yadda yadda {1:NM:=12.000:0.120} omtty doom {1:NM:=6/6} loppy loop"
html_input = "I am HTML"

结果应该是:
"yadda yadda I am HTML omtty doom I am HTML loppy loop"

但我得到的是:
"yadda yadda I am HTML omtty doom {1:NM:=6/6} loppy loop"

我错过了什么?

最佳答案

正如@SJR 在他们的评论中所说,您需要设置 Global正则表达式对象的属性为 True .该属性在 MSDN 上进行了描述:

Global - A Boolean property that indicates if the regular expression should be tested against all possible matches in a string. By default, Global is set to False.



所以在你的代码中变成:
Option Explicit

Sub ReplaceText()

Dim regEx As Object
Dim qtext As String
Dim html_input As String

' set up regex
Set regEx = CreateObject("VBScript.RegExp")
regEx.Pattern = "\{.*?\}"
regEx.Global = True '<-- set flag to true to replace all occurences of match

' input and replacement text
qtext = "yadda yadda {1:NM:=12.000:0.120} omtty doom {1:NM:=6/6} loppy loop"
html_input = "I am HTML"

' do replace
qtext = regEx.Replace(qtext, html_input)

' test output
MsgBox qtext

End Sub

关于regex - 使用正则表达式查找和替换字符串中模式的所有实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44906135/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com