【问题标题】:Find and replace all instances of a pattern in a string using Regular Expressions使用正则表达式查找和替换字符串中模式的所有实例
【发布时间】:2017-07-04 12:33:56
【问题描述】:

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

我错过了什么?

【问题讨论】:

  • 尝试添加regEx.Global = True
  • @SJR 您应该将其发布为答案,以便将来的用户可以轻松找到答案

标签: regex vba excel excel-2013


【解决方案1】:

正如@SJR 在他们的评论中所说,您需要将正则表达式对象的Global 属性设置为True。该属性描述于MSDN

Global - 一个布尔属性,指示是否应针对字符串中的所有可能匹配项测试正则表达式。默认情况下,全局设置为 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    • 2022-06-28
    • 1970-01-01
    相关资源
    最近更新 更多