VBScript:格式化字符串的最简单方法是什么?

时间:2009-12-03 15:44:40

标签: vbscript formatting string-formatting

我有以下格式: Value1为{0},Value2为{1}。

我需要用字符串替换括号中的数字。这在大多数语言中都可以使用string.Format或其他类似的东西轻松完成。我怎么能只使用vbscript呢?

我试过了:

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

它不起作用。任何解决方案?

5 个答案:

答案 0 :(得分:10)

我想要类似的东西并且不喜欢这些答案,因为它们意味着每个值有多行(忽略Beaner的答案是错误的语言!)所以我创建了以下内容:

Public Function StrFormat(FormatString, Arguments())
    Dim Value, CurArgNum

    StrFormat = FormatString

    CurArgNum = 0
    For Each Value In Arguments
        StrFormat = Replace(StrFormat, "{" & CurArgNum & "}", Value)
        CurArgNum = CurArgNum + 1
    Next
End Function

您可以使用以下(请注意,您需要在变量周围添加“Array()”)

formatString = "Test '{0}', '{2}', '{1}' and {0} again!"
Response.Write StrFormat(formatString, Array(1, 2, "three", "Unused"))
Response.Write StrFormat(formatString, Array(4, 5, "six", "Unused"))

将输出您期望的内容:

Test '1', 'three', '2' and 1 again!
Test '4', 'six', '5' and 4 again!

希望这对其他语言的人来说更自然。

答案 1 :(得分:9)

  

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

根据你的代码片段,我猜你直接认为替换mutate strFormat。它不像那样工作;您可以将结果分配给原始变量,如下所示:

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

您还可以指定另一个变量来存储更改的结果,如下所示:

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

答案 2 :(得分:4)

至于的答案到目前为止解决了格式化的问题(相反) 将字符串插入/拼接成字符串):

这个简单的类:

Class cFormat
  Private m_oSB
  Private Sub Class_Initialize()
    Set m_oSB = CreateObject("System.Text.StringBuilder")
  End Sub ' Class_Initialize
  Public Function formatOne(sFmt, vElm)
    m_oSB.AppendFormat sFmt, vElm
    formatOne = m_oSB.ToString()
    m_oSB.Length = 0
  End Function ' formatOne
  Public Function formatArray(sFmt, aElms)
    m_oSB.AppendFormat_4 sFmt, (aElms)
    formatArray = m_oSB.ToString()
    m_oSB.Length = 0
  End Function ' formatArray
End Class ' cFormat

通过COM利用.NET格式化VBScript。现在你可以做到:

-------- Interpolation
Use    |Value1 is {0} and Value2 is {1}.|
to get |Value1 is zero and Value2 is one.|
from   |zero one|

Use    |{0} x 2 => {0}{0}|
to get |once x 2 => onceonce|
from   |once|

-------- Cherrypicking
Use    |{6,4}: [{0}, {2}, {4}]|
to get |even: [0, 2, 4]|
from   |0 1 2 3 4 5 even odd|

Use    |{7,4}: [{5}, {3}, {1}]|
to get | odd: [5, 3, 1]|
from   |0 1 2 3 4 5 even odd|

-------- Conversions
Use    ||{0:D}| |{0:X}| |{0:N3}| |{0:P2}| (german locale!)|
to get ||123| |7B| |123,000| |12.300,00%| (german locale!)|
from   |123|

Use    ||{0}| |{0:U}| |{0:u}||
to get ||29.06.2012 14:50:30| |Freitag, 29. Juni 2012 12:50:30| |2012-06-29 14:50:30Z||
from   |29.06.2012 14:50:30|

Use    ||{0}| |{0:E1}| |{0:N1}| |{0:N2}| |{0:N3}||
to get ||1234,56| |1,2E+003| |1.234,6| |1.234,56| |1.234,560||
from   |1234,56|

-------- Alignment
Use    ||{0,1:D}| |{0,2:D}| |{0,-2:D}| |{0,5:D}| |{0,-5:D}||
to get ||12| |12| |12| |   12| |12   ||
from   |12|

如果您对测试/演示脚本感兴趣,可以进行一些实验 属于你自己:

Option Explicit

' Class cFormat ...

Dim oFormat : Set oFormat = New cFormat
Dim aTests  : aTests      = Array( _
    Array("Interpolation" _
      , Array( _
            Array(True,  "Value1 is {0} and Value2 is {1}.", Array("zero", "one")) _
          , Array(False, "{0} x 2 => {0}{0}"               , "once"              ) _
        } _
    ) _
  , Array("Cherrypicking" _
      , Array( _
            Array(True , "{6,4}: [{0}, {2}, {4}]", Array(0, 1, 2, 3, 4, 5, "even", "odd")) _
          , Array(True , "{7,4}: [{5}, {3}, {1}]", Array(0, 1, 2, 3, 4, 5, "even", "odd")) _
        } _
    ) _
  , Array("Conversions" _
      , Array( _
            Array(False, "|{0:D}| |{0:X}| |{0:N3}| |{0:P2}| (german locale!)", 123      ) _
          , Array(False, "|{0}| |{0:U}| |{0:u}|"                             , Now     ) _
          , Array(False, "|{0}| |{0:E1}| |{0:N1}| |{0:N2}| |{0:N3}|"         , 1234.56 ) _
        } _
    ) _
  , Array("Alignment" _
      , Array( _
            Array(False, "|{0,1:D}| |{0,2:D}| |{0,-2:D}| |{0,5:D}| |{0,-5:D}|", 12 ) _
        } _
    ) _
)
Dim sFormat : sFormat = "Use    |{0}|{3}to get |{1}|{3}from   |{2}|{3}"
Dim aData   : aData   = Array(0, 1, 2, vbCrLf)
Dim aTest
For Each aTest In aTests
    WScript.Echo "--------", aTest(0)
    Dim aSample
    For Each aSample In aTest(1)
        aData(0) = aSample(1)
        If aSample(0) Then
           aData(1) = oFormat.formatArray(aSample(1), aSample(2))
           aData(2) = Join(aSample(2))
        Else
           aData(1) = oFormat.formatOne(  aSample(1), aSample(2))
           aData(2) = aSample(2)
        End If
        WScript.Echo oFormat.formatArray(sFormat, aData)
    Next
    WScript.Echo
Next

要了解.NET中的格式,请从StringBuilder.AppendFormat Method (String, Object)Formatting Types开始。

请参阅herehere,了解如何将这样的类包含在您的脚本中(而不是复制和粘贴)。

答案 3 :(得分:0)

为什么不呢?这段代码在这里工作:

value1 = "1"
value2 = "2"

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

MsgBox strFormat

注意我为每次替换更新了strFormat值。

如果您需要更灵活的实现,可以使用正则表达式,但现在似乎不需要。

答案 4 :(得分:0)

这是一个很好的小函数,它的工作方式类似于.NET string.Format函数。我很快就这样做了,所以添加错误处理取决于你。我在VB6中做了这个并添加了对 Microsoft VBScript正则表达式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

示例:

StringFormat(“你好{0}。我希望你见{1}。他们都适用于{2}。{0}已经为{2}工作了15年。”,“布鲁斯”,“克里斯“,”凯尔“)

返回:

你好布鲁斯。我希望你能见到克里斯。他们都为凯尔工作。布鲁斯在凯尔工作了15年。