Yosoyke
Yosoyke

Reputation: 485

Get substring until first numeric character

like my title already explained, I want to get a substring of a string (who contains a address) and I would like to have only the street..

It's not possible to only take the text (non-numeric) chars, because then the box will remain. It's not possible to take substring till first space, because the streetname can contain a space..

For example 'developerstreet 123a' -> would like to have 'developerstreet' The 'a' is a box number of the house, which I'm not interested in..

How can I do this in VB.NET?

Upvotes: 3

Views: 6946

Answers (3)

GAP
GAP

Reputation: 1

text.Substring(0, text.IndexOfAny("0123456789"))

Upvotes: 0

Steven Doggart
Steven Doggart

Reputation: 43743

Parsing addresses is notoriously difficult, so I caution you to make sure that you a very deliberate about the choices you make. I would strongly recommend reviewing the documentation provided by the postal service. If these are US addresses, you should start by looking at the USPS Publication 28.

However, to answer your specific question, you can find the index of the first numeric character in a string by using the Char.IsDigit method. You may also want to take a look at the Char.IsNumber method, but that's probably more inclusive than what you really want. For instance, this will get the index of the first numeric character in the input string:

Dim index As Integer = -1
For i As Integer = 0 to input.Length - 1
    If Char.IsDigit(input(i)) Then
        index = i
        Exit For
    End If
Next

However, for complex string parsing, like this, I would suggest learning Regular Expressions. Getting the non-numeric portion at the beginning of a string becomes trivial with RegEx:

Dim m As Match = Regex.Match(input, "^\D+")
If m.Success Then
    Dim nonNumericPart As String = m.Value
End If

Here is the meaning of the regular expression in the above example:

  • ^ - The matching string must start at the beginning of the line
  • \D - Any non-numeric character
  • + - One or more times

Upvotes: 6

Tithi Patel
Tithi Patel

Reputation: 777

try this:

    Private Sub MyFormLoad(sender As Object, e As EventArgs) Handles Me.Load

     Dim str As String = "developerstreet 123a"
            Dim index As Integer = GetIndexOfNumber(str)
            Dim substr As String = str.Substring(0, index)
            MsgBox(substr)
    End Sub



       Public Function GetIndexOfNumber(ByVal str As String)
            For n = 0 To str.Length - 1
                If IsNumeric(str.Substring(n, 1)) Then
                    Return n
                End If
            Next
            Return -1
        End Function

output will be: developerstreet

Upvotes: 0

Related Questions