dimitrisd
dimitrisd

Reputation: 652

vbscript regular expression, replace between two string

I have this xml:

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

I want to apply a regular expression in VBScript to replace the content "+00xxxxxx" of the attribute ContactPrimaryMobile, simply change the number:

<ContactPrimaryMobile>+00xxxxxx</ContactPrimaryMobile>

I am new to vbscripting and my skills in creating the objects and applying the pattern are limited, so please can you help me converting this regex to use it in VBScript:

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

UPDATE I get this:

Object doesn't support this property or method: 'Submatches'

when executing:

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)

Upvotes: 2

Views: 1226

Answers (2)

I know you explicitly said and you have your answer but an alternative approach to getting the same end goal is to use an XML parser instead.

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"

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627609

First of all, VBScript regex does not support lookbehinds, you need to capture the part in between the two strings.

Next, you need to obtain the submatch by accessing the match object after you .Execute the regex match, and get its .Submatches(0):

Dim oRE, oMatches, objMatch
oRE.Pattern = "<ContactPrimaryMobile>(.*?)</ContactPrimaryMobile>"

and then

Set oMatches = oRE.Execute(s)
For Each objMatch In oMatches
  Wscript.Echo objMatch.Submatches(0)
Next

To replace, use the appropriate groupings and method:

oRE.Pattern = "(<ContactPrimaryMobile>).*?(</ContactPrimaryMobile>)"
' and then
s = oRE.Replace(s,"$1SOME_NEW_VALUE$2")

Upvotes: 6

Related Questions