regex - 使用正则表达式替换 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
解决方案
使用正则表达式: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"
推荐阅读
- mongodb - 带有嵌入文档的 Typegoose Alias
- c# - 间隔大数并删除 ,00 个小数
- prolog - 未绑定的输出列表如何绑定到输入列表元素加上 1?
- python-3.x - Matplotlib 导航工具栏重置 legendstyle
- javascript - 将 onDomContentLoaded 函数调用附加到 HTML 文件中的 DOM 对象
- java - 是否可以将正在运行的 Java 进程的状态保存到磁盘,然后在一段时间后恢复它?
- c++ - 如何在递归模式下使用 NtQueryDirectoryFile 检索完整的文件名?
- python - 如何将列表连接到节点到 Python networkx 中的单个节点?
- mongodb - MongoDB 聚合用实际文档替换 ObjectIds 数组
- excel - EXCEL:用上述值除以空格数填充空白单元格