Created
August 30, 2017 15:37
-
-
Save samwyse/b225b32ae1aea6fb27ad9c966b9ca90b to your computer and use it in GitHub Desktop.
Useful VB.net class definitions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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