我需要用自定义对象中的特定值替换标记有标记字符的通用子字符串。我已经编写了完成我想要的代码,虽然感觉很尴尬。我想知道是否有更复杂的解决方案来解决这个问题。具体来说,我想知道是否有一个快速函数来替换带有其他值的如此标记的子串,这取决于通常出现的子串。
这是我目前的代码:
Private Function DeGenerify(field_text As String)
Dim new_text As String, breakup As Variant
Dim i As Integer, lgth As Integer, prop As String
new_text = ""
breakup = Split(field_text)
For i = 0 To UBound(breakup)
If left(breakup(i), 1) = "$" Then
lgth = Len(breakup(i)) - 1
prop = right(breakup(i), lgth)
breakup(i) = CallByName(CFAL, prop, VbGet)
End If
new_text = new_text & breakup(i) & " "
Next i
DeGenerify = Trim(new_text) & "."
End Function
这具有预期的效果,即替换以" $"开头的字符串中的所有单词;具有" CFAL"的相应属性对象,前提是它是一个字符串。例如,文字:
所有$ STATION Fuel均为$ F_CLASS,与T.S.一致。 $ C_FlTbl
替换为文字:
所有Millstone 2燃料均为CE14x14级,与T.S.表 1-1e& 1-1F。
似乎必须已经存在一个函数才能获取那些$ xxxx字段并替换它们,而不必将字符串拆分并逐个进行。
有人知道这件事吗?
感谢您的帮助!
答案 0 :(得分:1)
您可以使用正则表达式提取所有标记,并使用Replace()替换值。
Option Explicit
Sub DeGenerifyTester()
Debug.Print DeGenerify("All $STATION Fuel is class $F_CLASS" & _
" consistent with T.S. $C_FlTbl", CFAL)
'>>> All STATION_value Fuel is class F_CLASS_value consistent with T.S. C_FlTbl_value
End Sub
Private Function DeGenerify(field_text As String, obj As Object)
Dim col, v, rv, prop
Set col = ExtractTokens(field_text)
rv = field_text
For Each v In col
Debug.Print "-->", v
prop = Replace(v, "$", "")
'rv = Replace(rv, v, prop & "_value") '<< for testing...
rv = replace(rv, v, CallByName(obj, prop, VbGet))
Next v
DeGenerify = rv
End Function
Function ExtractTokens(ByVal text As String) As Collection
Dim result As New Collection
Dim allMatches As Object, m As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.Pattern = "(\$[\w_]+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)
For Each m In allMatches
result.Add m
Next m
Set ExtractTokens = result
End Function
VBScript正则表达式: https://msdn.microsoft.com/en-us/library/ms974570.aspx