Regex 使用正则表达式查找并替换字符串中模式的所有实例
使用Excel VBA,我尝试替换如下所示的简单模式的所有实例:Regex 使用正则表达式查找并替换字符串中模式的所有实例,regex,vba,excel,excel-2013,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) 其中qtext和html\u
{some text}
使用其他常量字符串。所以我想找到所有用大括号括起来的文本,并用另一个字符串替换is(用大括号)
我使用以下代码:
Dim regEx As Object
Set regEx = CreateObject("VBScript.RegExp")
regEx.Pattern = "\{.*?\}"
qtext = regEx.Replace(qtext, html_input)
其中qtext
和html\u 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在他们的评论中所说,您需要将regex对象的
Global
属性设置为True
。有关该属性的说明,请参见:
全局-一个布尔属性,指示是否应针对字符串中所有可能的匹配项测试正则表达式。默认情况下,“全局”设置为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
选项显式
子文本()
Dim正则表达式作为对象
将qtext设置为字符串
将html_输入设置为字符串
'设置正则表达式
设置regEx=CreateObject(“VBScript.RegExp”)
regEx.Pattern=“\{.*.\}”
regEx.Global=True'尝试添加regEx.Global=True
@SJR您应该将其作为答案发布,以便未来用户可以轻松找到答案