VB.Net Extract numbers from string function
My request is one that can extract a number somewhat by a search.
Example: animalsOwned|4 would return an containing "4"
animals|3|2|1|3 would return an array containing "3", "2", "1", "3"
This would make it easier for me during a file stream reader. Thank you
Try regular expression. It's a powerful tool for simple text parsing.
Imports System.Text.RegularExpressions Namespace Demo Class Program Shared Function Main(ByVal args As String()) As Integer Dim array As Integer() = ExtractIntegers("animals|3|2|1|3") For Each i In array Console.WriteLine(i) Next Return 0 End Function Shared Function ExtractIntegers(ByVal input As String) As Integer() Dim pattern As String = "animals(\|(?<number>[0-9]+))*" Dim match As Match = Regex.Match(input, pattern) Dim list As New List(Of Integer) If match.Success Then For Each capture As Capture In match.Groups("number").Captures list.Add(Integer.Parse(capture.Value)) Next End If Return list.ToArray() End Function End Class End Namespace
Dim astring = "ABCDE|1|2|3|4" Dim numbers = (From s In astring Where Char.IsDigit(s) Select Int32.Parse(s)).ToArray()
This LINQ statement should help. It simply checks each character in a string to see if it's a digit. Note that this only applies to single digit numbers. It becomes a bit more complicated if you want "ABC123" to return 123 vs. 1, 2, 3 array.