Skip to content

Instantly share code, notes, and snippets.

@samwyse
Created August 30, 2017 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samwyse/b225b32ae1aea6fb27ad9c966b9ca90b to your computer and use it in GitHub Desktop.
Save samwyse/b225b32ae1aea6fb27ad9c966b9ca90b to your computer and use it in GitHub Desktop.
Useful VB.net class definitions
Imports Microsoft.VisualBasic
Public Class FormatFromDictionary
Private format As String
Private safe As Boolean
Private rex As System.Text.RegularExpressions.Regex
Sub New(format As String, Optional safe As Boolean = False)
Me.format = format
Me.safe = safe
Me.rex = New System.Text.RegularExpressions.Regex("\{([^,:}]+)([,:][^}]*)?\}")
End Sub
Function Replace(ByVal dict As Dictionary(Of String, Object)) As String
Return rex.Replace(format,
Function(ByVal match As System.Text.RegularExpressions.Match) As String
Dim key As String = match.Groups(1).Value
Dim extra = match.Groups(2)
Try
If extra.Success Then
Return String.Format("{0" & extra.Value & "}", dict(key))
End If
Return dict(key)
Catch ex As Exception
If safe Then
If extra.Success Then
Return String.Format("{0" & extra.Value & "}", match.ToString)
End If
Return match.ToString
End If
Throw
End Try
End Function)
End FunctionEnd Class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment