7

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

我需要用字符串替换括号中的数字。这很容易在大多数语言中使用 string.Format 或类似的东西来完成。如何仅使用 vbscript 执行此操作?

我试过了:

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

这没用。有什么解决办法吗?

4

5 回答 5

12

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

根据您的代码片段,我猜您认为 ReplacestrFormat直接发生变异。它不是那样工作的;您将结果分配给原始变量,如下所示:

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

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

strFormat2 = Replace (strFormat, "{0}", value1)
于 2009-12-03T15:51:40.533 回答
11

我想要类似的东西并且不喜欢这些答案中的任何一个,因为它们意味着每个值都有多行(忽略 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!

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

于 2012-06-29T10:05:49.000 回答
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 为 VBScript 使用 .NET 格式。现在你可以这样做:

-------- 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开始。

请参阅此处此处了解将此类类包含(而不是复制和粘贴)到您的脚本中的想法。

于 2012-06-29T13:11:05.893 回答
1

这是一个不错的小函数,其工作原理类似于 .NET string.Format 函数。我很快就做到了,所以添加错误处理取决于你。我在 VB6 中执行此操作并添加了对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

例子:

StringFormat("您好 {0}。我想见见 {1}。他们都为 {2} 工作。{0} 为 {2} 工作了 15 年。", "Bruce", "Chris", “凯尔”)

回报:

你好布鲁斯。我想让你见见克里斯。他们都为凯尔工作。布鲁斯为凯尔工作了 15 年。

于 2009-12-03T16:59:35.047 回答
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值。

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

于 2009-12-03T15:47:32.430 回答