VB.Net Extract numbers from string function

蹲街弑〆低调 提交于 2019-12-08 10:39:48

问题


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


回答1:


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



回答2:


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.




回答3:


I haven't programmed VB for awhile but I'll give you some pseudo code: First, loop through each line of file. Call this variable Line. Then, take the index of what you're searching for: like Line.indexOf("animalsOwned") If it returns -1 it isn't there; continue. Once you find it, add the Index variable to the length of the search string and 1. (Index=Index+1+Len(searchString)) Then, take a substring starting there, and end at the end of the line. Explode the substring by | characters, then add each into an array. Return the array.

Sorry that I can't give you much help, but I'm working on an important PHP website right now ;).




回答4:


You can do a variable.Split("|") and then assign each piece to an array level.

You can do a count on string and with a while or for loop, you can assign the splited sections to array levels. Then you can do a IsNumeric() check for each array level.



来源:https://stackoverflow.com/questions/14064468/vb-net-extract-numbers-from-string-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!