Rajasekar
Rajasekar

Reputation: 18948

Regular expression to extract numbers from long string containing lots of punctuation

I am trying to separate numbers from a string which includes %,/,etc for eg (%2459348?:, or :2434545/%). How can I separate it, in VB.net

Upvotes: 0

Views: 6328

Answers (4)

JaredPar
JaredPar

Reputation: 754645

Here's a function which will extract all of the numbers out of a string.

Public Function GetNumbers(ByVal str as String) As String
  Dim builder As New StringBuilder()
  For Each c in str
    If Char.IsNumber(c) Then
      builder.Append(c)
    End If
  Next
  return builder.ToString()
End Function

Upvotes: 0

Ahmad Mageed
Ahmad Mageed

Reputation: 96477

This should do:

Dim test As String = "%2459348?:"
Dim match As Match = Regex.Match(test, "\d+")

If match.Success Then
  Dim result As String = match.Value
  ' Do something with result
End If

Result = 2459348

Upvotes: 0

Ken
Ken

Reputation: 352

You could loop through each character of the string and check the .IsNumber() on it.

Upvotes: 0

marc.d
marc.d

Reputation: 3844

you want only the numbers right?

then you could do it like this

    Dim theString As String = "/79465*44498%464"
    Dim ret = Regex.Replace(theString, "[^0-9]", String.Empty)

hth

edit:

or do you want to split by all non number chars? then it would go like this

Dim ret = Regex.Split(theString, "[^0-9]")

Upvotes: 6

Related Questions