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

Answers


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.


Need Your Help

Binding data in created dropdown from ajax data

c# javascript .net ajax asp.net-mvc-4

I have following dropdown created in cshtml page:

disabling imageSmoothingEnabled by default on multiple canvases

javascript canvas html5-canvas

I'm creating a browser-based game that uses layered canvases and sprite images, and for visual and performance reasons I would like to disable imageSmoothingEnabled by default. It's my understandin...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.