使用正则表达式查找并替换字符串中某个模式的所有实例
Find and replace all instances of a pattern in a string using Regular Expressions
使用 Excel VBA,我正在尝试替换一个简单模式的所有实例,如下所示:
{some text}
与其他一些常量字符串。所以我想找到所有用大括号括起来的文本,并用另一个字符串替换(用大括号)。
我使用以下代码:
Dim regEx As Object
Set regEx = CreateObject("VBScript.RegExp")
regEx.Pattern = "\{.*?\}"
qtext = regEx.Replace(qtext, html_input)
其中 qtext
和 html_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
使用 Excel VBA,我正在尝试替换一个简单模式的所有实例,如下所示:
{some text}
与其他一些常量字符串。所以我想找到所有用大括号括起来的文本,并用另一个字符串替换(用大括号)。
我使用以下代码:
Dim regEx As Object
Set regEx = CreateObject("VBScript.RegExp")
regEx.Pattern = "\{.*?\}"
qtext = regEx.Replace(qtext, html_input)
其中 qtext
和 html_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