Solved

In vb.net, how to eliminate non-numbers in a string?

Posted on 2016-10-07
3
79 Views
Last Modified: 2016-10-12
The string should have nothing but numbers in it, but if it does, I need to find out if there is an easy way to eliminate the non-numeric characters.

I ran into a situation where there was a "#" in the field, so for that situation I used this code:

psWork1 = psWork1.Replace("#", "")

...and that worked great.  But I need code that will handle ANY non-numbers in the string.  TIA
0
Comment
Question by:sasllc
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 12

Accepted Solution

by:
funwithdotnet earned 200 total points
ID: 41834274
Here's a helper method I use:
                ''' <summary>
                ''' Filters non-numeric characters from a String.
                ''' </summary>
                ''' <param name="input">The String value to be filtered.</param>
                ''' <returns>Returns only the numeric characters from the supplied String.</returns>
                Public Shared Function NumericFilter(ByVal input As String) As String
                    Dim output As String = ""
                    If input.Length > 0 Then
                        Dim tempChar() As Char = input.ToCharArray()
                        For Each myChar As Char In tempChar
                            If Char.IsDigit(myChar) Then
                                output &= myChar.ToString
                            End If
                        Next
                    End If
                    Return output
                End Function

Open in new window

0
 
LVL 26

Assisted Solution

by:Shaun Kline
Shaun Kline earned 150 total points
ID: 41834279
You could use a Regular Expression to do this. Your matching pattern would be a negation of the acceptable characters:
Imports System.Text.RegularExpression

psWork1 = Regex.Replace(psWork1, "[^0-9]", "")

Open in new window

The [^0-9] in the code above should equate to all characters except 0-9.
0
 
LVL 34

Assisted Solution

by:it_saige
it_saige earned 150 total points
ID: 41834291
Couple of ways, look at each character in the string and determine if it is numeric, if it is, keep it or using regular expressions to identify the characters you want to keep  and replacing all others:
Imports System.Text.RegularExpressions

Module Module1
	Sub Main()
		Const stripthis = "Th1s 1s 4 str1ng w1th ch4r4ct3rs fr0m wh1ch w3 0nly w4nt th3 n#mb3rs."

		Console.WriteLine("Using a for loop: {0}", UsingForLoop(stripthis))
		Console.WriteLine("Using a foreach loop: {0}", UsingForEachLoop(stripthis))
		Console.WriteLine("Using linq: {0}", UsingLinq(stripthis))
		Console.WriteLine("Using regular expressions: {0}", UsingRegEx(stripthis))
		Console.ReadLine()
	End Sub

	Function UsingForLoop(source As String) As String
		Dim result = String.Empty
		For i = 0 To source.Length - 1
			If IsNumeric(source(i)) Then
				result += source(i)
			End If
		Next
		Return result
	End Function

	Function UsingForEachLoop(source As String) As String
		Dim result = String.Empty
		For Each c As Char In source
			If IsNumeric(c) Then
				result += c
			End If
		Next
		Return result
	End Function

	Function UsingLinq(source As String) As String
		Return New String((From c As Char In source Where IsNumeric(c) Select c).ToArray())
	End Function

	Function UsingRegEx(source As String) As String
		Return Regex.Replace(source, "[^0-9]", "")
	End Function
End Module

Open in new window


Produces the following output -Capture.JPG
-saige-
0

Featured Post

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question