Regex replace

G

Guoqi Zheng

Dear Sir, I need to use regex to replace some string.

Below is what I use.

output = "sample data <href=""xlink:GG44-33"">, part two
<href=""xlink:GG55-123"">"
Dim regEx
Set regEx = New RegExp
regEx.Pattern = "href=\""(xlink:.*?)\"""
output = regEx.Replace(output,"href="&chr(34) &
GetDatabaseLink("$1")&chr(34))

Function GetDatabaseLink(Byval input)
'' query database based on "input" value and return value on database.
End Function

the value inside <href> tag needs to be replaced by real value from
database. Function GetDatabaseLink get the value from match string and send
it to database for query. What the database receive right now is the value
of "$1", instead of "xlink:GG44-33" and "xlink:GG55-123" in this case.

What did I do wrong?


Regards,

Guoqi Zheng
 
A

Anthony Jones

Guoqi Zheng said:
Dear Sir, I need to use regex to replace some string.

Below is what I use.

output = "sample data <href=""xlink:GG44-33"">, part two
Dim regEx
Set regEx = New RegExp
regEx.Pattern = "href=\""(xlink:.*?)\"""
output = regEx.Replace(output,"href="&chr(34) &
GetDatabaseLink("$1")&chr(34))

Function GetDatabaseLink(Byval input)
'' query database based on "input" value and return value on database.
End Function

the value inside <href> tag needs to be replaced by real value from
database. Function GetDatabaseLink get the value from match string and send
it to database for query. What the database receive right now is the value
of "$1", instead of "xlink:GG44-33" and "xlink:GG55-123" in this case.

What did I do wrong?

RegEx will replace any $1 it finds in the string passed to it. The
expression:-
"href="&chr(34) & GetDatabaseLink("$1")&chr(34)
is evaluated first then its result passed into the the Replace method.
Therefore GetDataBaseLink("$1") executes as is with no replacement of $1.

First thing I would do is lose the extraneous href= etc from around the
pattern. Use:-

regEx.Pattern = """xlink:[^""]*"
regEx.Global = True

output = regEx.Replace(output, GetRef("ReplaceXLink"))

Function ReplaceXLink(rsXLink, vlOffset, rsSource)
ReplaceXLink = """" & GetDatabaseLink(Mid(rsXLink, 2, Len(rsXink) -2)) &
""""
End Function

This will globally replace all xlinks in the string with the appropriate
value looked up from the DB.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top