regex - vbscript 正则表达式,在两个字符串之间替换
问题描述
我有这个xml:
<doc>
<ContactPrimaryEmail></ContactPrimaryEmail>
<ContactAlternateEmail></ContactAlternateEmail>
<ContactPrimaryMobile>+00xxxxxx</ContactPrimaryMobile>
<ContactAlternateMobile></ContactAlternateMobile>
</doc>
我想在VBScript中应用正则表达式来替换属性ContactPrimaryMobile的内容“ +00xxxxxx ” ,只需更改数字:
<ContactPrimaryMobile>+00xxxxxx</ContactPrimaryMobile>
我是 vbscripting 新手,我在创建对象和应用模式方面的技能有限,所以请你帮我转换这个正则表达式以在 VBScript 中使用它:
(?<=\<ContactPrimaryMobile\>)(.*)(?=\<\/ContactPrimaryMobile)
更新我得到这个:
对象不支持此属性或方法:“子匹配”
执行时:
Dim oRE, oMatches
Set oRE = New RegExp
oRE.Pattern = "<ContactPrimaryMobile>(.*?)</ContactPrimaryMobile>"
oRE.Global = True
Set oMatches = oRE.Execute("<doc><ContactPrimaryEmail></ContactPrimaryEmail><ContactAlternateEmail></ContactAlternateEmail><ContactPrimaryMobile>+00xxxxxx</ContactPrimaryMobile><ContactAlternateMobile></ContactAlternateMobile></doc>")
Wscript.Echo oMatches.Submatches(0)
解决方案
首先,VBScript 正则表达式不支持lookbehinds,您需要捕获两个字符串之间的部分。
接下来,您需要在正则表达式匹配后通过访问匹配对象来获取子.Execute
匹配,并获取其.Submatches(0)
:
Dim oRE, oMatches, objMatch
oRE.Pattern = "<ContactPrimaryMobile>(.*?)</ContactPrimaryMobile>"
进而
Set oMatches = oRE.Execute(s)
For Each objMatch In oMatches
Wscript.Echo objMatch.Submatches(0)
Next
要替换,请使用适当的分组和方法:
oRE.Pattern = "(<ContactPrimaryMobile>).*?(</ContactPrimaryMobile>)"
' and then
s = oRE.Replace(s,"$1SOME_NEW_VALUE$2")
推荐阅读
- macos - 为什么我在一个什么都不做的程序中有内存泄漏(在 mac OS 10.13.6 上使用 Valgind)?
- pandas - Pandas 在多列上应用函数
- html - 背景上的高度 100 百分比不起作用?
- hugo - 在简码定义中使用简码
- node.js - 来自谷歌存储库的 NPM 依赖项
- sql-server-2000 - 使用由 alter table 添加的临时表中的新列不起作用
- python - 使用漂亮的汤python从html标签中提取信息
- angular - public get 从 auth 服务返回一个权限布尔值,初始化为 false 并在 NGRX 存储返回值但未定义时修改
- haskell - 在方法上获取非详尽的模式异常
- excel - 如何修复 - Excel VBA 复制和粘贴值 - ThisWorkbook 错误