Search code examples
regexvbscriptasp-classic

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)

Solution

  • 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")