Reputation: 1149
I know how to test for a pattern using the 'like' operator in VB.NET but what I wish to do is test for the pattern that can appear at any point in the string and return it.
I.e
Dim _MyString As String = "Dave 01-LYJX01PC01 XXYZABC"
Dim _MyString2 As String = "Dave XXYZABC 01-LYJX01PC01"
If _MyString LIKE "##-????##??##" Then
Console.WriteLine(_MyString )
End If
Now I know the above but what I wish to do is return the text that matches the pattern.
I could be missing something really basic here, but I've looked that long im struggling and need another opinion.
Cheers
Upvotes: 3
Views: 3345
Reputation: 626845
You can use the following regex:
\d{2}-\p{L}{4}\d{2}\p{L}{2}\d{2}
See demo
If it is a substring that is always a whole word, enclose this pattern with word boundaries: \b\d{2}-\p{L}{4}\d{2}\p{L}{2}\d{2}\b
.
VB.NET snippet:
Dim my_rx As Regex = New Regex("\d{2}-\p{L}{4}\d{2}\p{L}{2}\d{2}")
Dim my_matches As List(Of String) = my_rx.Matches("Dave 01-LYJX01PC01 XXYZABC").Cast(Of Match)().Select(Function(m) m.Value).ToList()
Dim my_matches2 As List(Of String) = my_rx.Matches("Dave XXYZABC 01-LYJX01PC01").Cast(Of Match)().Select(Function(m) m.Value).ToList()
UPDATE
Since you will always have 1 match in the input string, you can use simple code:
Dim my_result As Match = my_rx.Match("Dave XXYZABC 01-LYJX01PC01")
If my_result.Success Then
Console.WriteLine(my_result)
End If
See IDEONE demo
Upvotes: 2
Reputation: 690
What you need is write string 'Matches' in console?
If right you must encap 'Matches' with double quote.
Console.WriteLine("Matches")
Upvotes: -1