首页 > 解决方案 > 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)

标签: regexvbscriptasp-classic

解决方案


首先,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")

推荐阅读