Reputation: 59
I have 2 variables:
Dim filename as string = "Test2020.csv"
Dim fileSearch as string = "Test*.csv"
Filename is the name of the file and file search is the pattern that was used to find it.
I am in a situation where I need to check if the filename matches the pattern.
The way I was going to do it is take every string before the *: "Test" and everything after the *: ".csv" and check if the filename starts and ends with these. Is there an easier and simpler way to find if one string pattern matches the other.
Please note, I am comparing 2 strings and not trying to locate a file in a directory.
Upvotes: 0
Views: 507
Reputation: 39152
VB.Net does have the LEGACY Like Operator:
Compares a string against a pattern.
You can't use it in .NET Core
or .NET Standard
, though:
The Like operator is currently not supported in .NET Core and .NET Standard projects.
If that doesn't bother you, then here's an example:
Dim filename As String = "Test2020.csv"
Dim fileSearch As String = "Test*.csv"
If filename Like fileSearch Then
Debug.Print("Passed the pattern test.")
Else
Debug.Print("Did NOT pass the pattern test.")
End If
Upvotes: 0
Reputation: 15101
You can use String.StartWith()
and String.EndsWith()
.
Private Function TestPatternMatch(FileName As String) As Boolean
If FileName.StartsWith("Test") AndAlso FileName.EndsWith(".csv") Then
Return True
Else
Return False
End If
End Function
Usage:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Debug.Print(TestPatternMatch("Test2020.csv").ToString)
End Sub
Upvotes: 0
Reputation: 782
Try this:
This returns true:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fileSearch As String = "Test1929.csv"
Dim FileNameMatch As Boolean = fileSearch Like "Test####[.]csv"
TextBox1.Text = FileNameMatch
End Sub
This returns false:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fileSearch As String = "Testabcd.csv"
Dim FileNameMatch As Boolean = fileSearch Like "Test####[.]csv"
TextBox1.Text = FileNameMatch
End Sub
Upvotes: 1