首页 > 解决方案 > 使用正则表达式替换 VBA

问题描述

我正在尝试使用 VBA 代码编辑 XML 文件。以下是我正在尝试做的示例

justification="left" dimensionsHeight="1" dimensionsWidth="19" characterOffset="0".

我想要的是当我搜索文档时,如果我找到一个名为 justification 的字符串,我想摆脱从对齐开始到我指定的字符长度的文本。例如:在这种情况下,我想摆脱 justification upto dimensionswidth="19" ,我的结果应该包含 just characterOffset="0"。我正在尝试使用 Instr & Replace 函数,但问题是引号中的字符是变量,我的代码不适用于所有情况。任何想法的家伙

这是我现在拥有的代码

If InStr(1, LinesB(j), "Justification") Then

LinesB(j) = Replace(LinesB(j), "justification=" + Chr(34) + "left" + Chr(34) + "dimensionsHeight=" + Chr(34) + "1" + Chr(34) + "dimensionsWidth=" + Chr(34) + "19", "")

End If

标签: regexvbaexcel

解决方案


使用正则表达式:justification.*?(?=\scharacterOffset)

演示

请参阅此链接以了解如何在 VBA 中使用正则表达式进行替换

样本:

Dim regex As Object, str As String
Set regex = CreateObject("VBScript.RegExp")

With regex
  .Pattern = "justification.*?(?=\scharacterOffset)"
End With

str = "justification="left" dimensionsHeight="1" dimensionsWidth="19" characterOffset="0""   'might need to escape "
Debug.Print regex.Replace(str, "") 
'Result: characterOffset="0"

推荐阅读