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

标签 regex vba excel excel-2013

使用 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/

相关文章:

php - 如何在php中使用搜索和替换句子中的所有匹配词

VBA 灰色复选框

VBA 宏突出显示当前电子邮件中选定的文本

vba - 将变量值插入带有文本VBA的单元格

sql - 当一个值被部分屏蔽时比较 oracle 中的值

c# - 正则表达式模式中的相同变量

excel - 使用宏以编程方式删除我的工作簿中的所有代码

sql - 转账中带破折号的数字不断减

excel - VLookUp 函数 VBA - 未返回所需值

java - 如何通过java正则表达式在长字符串中grep相同格式的子字符串?