【问题标题】:vbscript regular expression, replace between two stringvbscript 正则表达式,在两个字符串之间替换
【发布时间】:2018-09-14 19:15:31
【问题描述】:

我有这个 xml:

<doc>
<ContactPrimaryEmail></ContactPrimaryEmail>
<ContactAlternateEmail></ContactAlternateEmail> 
<ContactPrimaryMobile>+00xxxxxx</ContactPrimaryMobile>
<ContactAlternateMobile></ContactAlternateMobile> 
</doc>

我想在 VBScript 中应用正则表达式来替换 ContactPrimaryMobile 属性的 content "+00xxxxxx" strong>,只需更改数字即可:

<ContactPrimaryMobile>+00xxxxxx</ContactPrimaryMobile>

我是 vbscripting 的新手,我在创建对象和应用模式方面的技能有限,所以请你帮我转换这个正则表达式以在 VBScript 中使用它:

(?<=\<ContactPrimaryMobile\>)(.*)(?=\<\/ContactPrimaryMobile)

更新 我明白了:

对象不支持此属性或方法:'Submatches'

执行时:

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)

【问题讨论】:

  • 使用&lt;ContactPrimaryMobile&gt;(.*?)&lt;/ContactPrimaryMobile&gt; 并获取match.Submatches(0) 值。如果您需要更具体的帮助,请显示您的代码。
  • 我得到这个对象不支持这个属性或方法:'Submatches' 执行时:Dim oRE, oMatches Set oRE = New RegExp oRE.Pattern = "(.*?)" oRE.Global = True Set oMatches = oRE.Execute("+00xxxxxx") Wscript.Echo oMatches.Submatches(0) 还有什么帮助吗?
  • 请将其添加到问题正文中。您为什么要在匹配集合上获取子匹配?访问第一项。 Wscript.Echo oMatches(0).Submatches(0)
  • 非常感谢您的回复!
  • 不只是一个,但我真正需要的是用一个新的替换xml中的数字。

标签: regex vbscript asp-classic


【解决方案1】:

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

【讨论】:

  • 很好,我明白了!现在,如何更新字符串中的数字?
【解决方案2】:

我知道你明确表示 并且你有你的答案,但实现相同最终目标的另一种方法是改用 XML 解析器。

option explicit

dim xmldoc
set xmldoc = CreateObject("MSXML2.DomDocument")
xmldoc.load "doc.xml"
dim primaryMobileNode
set primaryMobileNode = xmldoc.selectSingleNode("/doc/ContactPrimaryMobile")
primaryMobileNode.text = "new value"
xmldoc.save "changed-doc.xml"

【讨论】:

  • 感谢您的回复。好点,我也是这么想的。但我不会从文件中读取 xml。它来自数据库作为 adodb 对象。我认为使用正则表达式会更快
猜你喜欢
  • 2015-03-26
  • 1970-01-01
  • 1970-01-01
  • 2020-08-02
  • 1970-01-01
  • 2010-09-23
  • 2022-07-13
  • 2017-12-20
  • 1970-01-01
相关资源
最近更新 更多