views:

267

answers:

3

I have the following format: Value1 is {0} and Value2 is {1}.

I need to replace the numbers in the brackets with strings. This is easily done in most languages using string.Format or something along those lines. How can I do this using only vbscript?

I've tried:

Replace (strFormat, "{0}", value1)  
Replace (strFormat, "{1}", value2)

It does not work. Any solutions?

+1  A: 

Why not? This code works here:

value1 = "1"
value2 = "2"

strFormat = "Value1 is {0} and Value2 is {1}."
strFormat = Replace (strFormat, "{0}", value1)  
strFormat = Replace (strFormat, "{1}", value2)

MsgBox strFormat

Note I update my strFormat value for every replace.

If you needs a more flexible implementation, you can go with a regular expression, but doesn't seems required now.

Rubens Farias
+4  A: 

Replace (strFormat, "{0}", value1)

Based on your code snip, I'm guessing you believe Replace mutates strFormat directly. It doesn't work like that. You need another variable to store the changed results like this:

strFormat2 = Replace (strFormat, "{0}", value1)
JasDev
Hehe, Thanks. It's always something simple.
Paxenos
he doesnt need _another_ variable, but just to update original string.
Rubens Farias
+2  A: 

Here's a nice little function that works something like the .NET string.Format function. I did this quickly so adding err handling is up to you. I did this in VB6 and added a reference to Microsoft VBScript Regular Expressions 5.5

Public Function StringFormat(ByVal SourceString As String, ParamArray Arguments() As Variant) As String
   Dim objRegEx As RegExp  ' regular expression object
   Dim objMatch As Match   ' regular expression match object
   Dim strReturn As String ' the string that will be returned

   Set objRegEx = New RegExp
   objRegEx.Global = True
   objRegEx.Pattern = "(\{)(\d)(\})"

   strReturn = SourceString
   For Each objMatch In objRegEx.Execute(SourceString)
      strReturn = Replace(strReturn, objMatch.Value, Arguments(CInt(objMatch.SubMatches(1))))
   Next objMatch

   StringFormat = strReturn

End Function

Example:

StringFormat("Hello {0}. I'd like you to meet {1}. They both work for {2}. {0} has worked for {2} for 15 years.", "Bruce", "Chris", "Kyle")

Returns:

Hello Bruce. I'd like you to meet Chris. They both work for Kyle. Bruce has worked for Kyle for 15 years.

Beaner
A few adjustments might be made for VBScript, but this function looks like it might be versatile than just a simple Replace function.
Chris