2017-05-09 57 views
0

我需要用自定義對象中的特定值替換標記爲具有標誌字符的通用子字符串。我寫了完成我想要的代碼,但感覺很尷尬。我想知道這個問題是否有更復雜的解決方案。具體來說,我想知道是否有一個快速函數用其他值替換如此標記的子字符串,這取決於一般發生的子字符串。使用標誌字符替換具有對象屬性的子字符串

這裏是我當前的代碼:

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

替換爲文本:

所有磨石2燃料類CE14x14與T.S.一致表 1-1e & 1-1f。

看起來好像一個函數必須已經存在才能抓住這些$ xxxx字段並替換它們,而不必將字符串分割開來並一個接一個地完成。

有人知道這樣的事情嗎?

感謝您的幫助!

回答

0

您可以使用正則表達式來提取所有的標記,並使用Replace()替換值。

Option Explicit 

Sub DeGenerifyTester() 
    Debug.Print DeGenerify("All $STATION Fuel is class $F_CLASS consistent with T.S. $C_FlTbl") 
    '>>> 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) 

    Dim col, v, rv 
    Set col = ExtractTokens(field_text) 
    rv = field_text 

    For Each v In col 
     Debug.Print "-->", v 
     rv = Replace(rv, v, Replace(v, "$", "") & "_value") '<< for testing... 
     'rv = replace(rv, v, CallByName(CFAL, 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