传递模式和相应的替换字符串以起作用

时间:2016-04-21 09:04:41

标签: arrays vba vbscript

我想使用VBScript将字典类型数组传递给Function。

我想创建一个可以在这样的数组上运行的正则表达式函数。

例如

array = [pat1:rep1, pat2:rep2]
'or any valid VBScript array or dictionary format

txtLn = regs()

Function regs(array)
  Set regEx_ = new regExp
  With regEx_
    .Global = True
    .MultiLine = True
    .IgnoreCase = True

    .Pattern = pat1:rep1
    txtLn = regEx_.replace(txtLn, replace pattarn 1 from array)

    .Pattern = pat1:rep2
    txtLn = regEx_.replace(txtLn, replace pattarn 2 from array)

    'and so on till the length of array

  txtLn = regs
End function

我知道这是一个广泛的问题,但我没有任何想法。 我期待的是另一个想法。 请指点我的方向

2 个答案:

答案 0 :(得分:2)

看起来你真的想传递字典,因为你想传递映射到替换字符串的模式。尝试这样的事情:

Function regs(d)
  Set regEx_ = New RegExp
  With regEx_
    .Global = True
    .MultiLine = True
    .IgnoreCase = True

    For Each p In d.Keys
      .Pattern = p
      txtLn = regEx_.Replace(txtLn, d(p))
    Next
  End With

  regs = txtLn
End Function

请注意,您需要将txtLn指定给函数名称,以将结果传递回调用者。将txtLn作为参数传递给函数而不是让函数对全局变量进行操作也是一种很好的做法。

答案 1 :(得分:1)

你说你需要想法 - 这是我如何将字典传递给子。在这个例子中,我生成一个带有键的字典,数字从0到9,我将它传递给PrintDictionary子,以便打印它:

Option Explicit

Public Sub NumbersAndDictionary()

    Dim l_counter_0     As Long
    Dim l_counter_1     As Long
    Dim l_counter_2     As Long
    Dim l_value         As Long

    Dim my_dict         As Object
    Dim my_str          As String

    Set my_dict = CreateObject("Scripting.Dictionary")

    For l_counter_0 = 65 To 76
        my_str = CStr(l_counter_0)
        For l_counter_1 = 1 To Len(my_str)
            l_value = CLng(Mid(my_str, l_counter_1, 1))

            If Not my_dict.Exists(l_value) Then
                my_dict.Add l_value, 1
            Else
                my_dict(l_value) = my_dict(l_value) + 1
            End If

        Next l_counter_1
    Next l_counter_0

    Call PrintDictionary(my_dict)

    Set my_dict = Nothing

End Sub

Public Sub PrintDictionary(my_dict As Object)

    Dim l_counter_0     As Long

    For l_counter_0 = 0 To my_dict.Count - 1
        Debug.Print l_counter_0; " "; my_dict.Item(l_counter_0)
    Next l_counter_0
End Sub