有很多因素会影响性能,所以在不了解所有细节的情况下很难说哪种方法最有效。然而,当谈到编码的简单性时,使用RegExMatchEvaluator
将是一个很好的选择。我相信你会同意它比你目前使用的任何东西都要干净:
Public Function ReplacePlaceholders(data As String) As String
Dim r As New Regex("\[\[(?<placeholder>.*?)\]\]")
data = r.Replace(data, New MatchEvaluator(AddressOf PlaceHolderReplacementEvaluator))
End Function
Private Function PlaceHolderReplacementEvaluator(match As Match) As String
Dim name As String = match.Groups("placeholder").Value
Return LookUpValueByPlaceholderName(name) ' Replace with value lookup logic here
End Function
如果数据中占位符的总数将相当少,并且可能的占位符列表很小,那么最好只列出它们的值并像这样替换它们:
Public Function ReplacePlaceholders(data As String) As String
Dim placeHolders As Dictionary(Of String, String) = LoadPlaceHolders()
For Each i As KeyValuePair(Of String, String) In placeHolders
data = data.Replace(i.Key, i.Value)
Next
Return data
End Function
Private Function LoadPlaceHolders() As Dictionary(Of String, String)
Dim placeholders As New Dictionary(Of String, String)
' Load data here
Return placeholders
End Function
但是,如果您真的想要最有效的解决方案,那么逐个字符并在执行过程中附加到 aStringBuilder
或 outputStream
将是您的最佳选择。它不会很漂亮,但是如果您将所拥有的内容发布到CodeReview,可能会有一些人可以找到使它变得不那么难看的方法:)