Sriram
Sriram

Reputation: 121

Remove special characters from a string

These are valid characters:

a-z
A-Z
0-9
-
/ 

How do I remove all other characters from my string?

Upvotes: 12

Views: 95559

Answers (5)

Mr.B
Mr.B

Reputation: 3787

I've used the first solution from LukeH, but then realized that this code replaces the dot for extension, therefore I've just upgraded the code slightly:

 Dim fileNameNoExtension As String = Path.GetFileNameWithoutExtension(fileNameWithExtension)
 Dim cleanFileName As String = Regex.Replace(fileNameNoExtension, "[^A-Za-z0-9\-/]", "") & Path.GetExtension(fileNameWithExtension)

cleanFileName will the file name with no special characters with extension.

Upvotes: 0

But Jao
But Jao

Reputation: 21

Dim txt As String
txt = Regex.Replace(txt, "[^a-zA-Z 0-9-/-]", "")

Upvotes: 1

Anand Vishwakarma
Anand Vishwakarma

Reputation: 11

Function RemoveCharacter(ByVal stringToCleanUp)
    Dim characterToRemove As String = ""
        characterToRemove = Chr(34) + "#$%&'()*+,-./\~"
        Dim firstThree As Char() = characterToRemove.Take(16).ToArray()
        For index = 1 To firstThree.Length - 1
            stringToCleanUp = stringToCleanUp.ToString.Replace(firstThree(index), "")
        Next
        Return stringToCleanUp
End Function

Upvotes: 0

LukeH
LukeH

Reputation: 269388

Dim cleanString As String = Regex.Replace(yourString, "[^A-Za-z0-9\-/]", "")

Upvotes: 27

Sidharth Panwar
Sidharth Panwar

Reputation: 4654

Use either regex or Char class functions like IsControl(), IsDigit() etc. Get a list of these functions here: http://msdn.microsoft.com/en-us/library/system.char_members.aspx

Here's a sample regex example:

(Import this before using RegEx)

Imports System.Text.RegularExpressions

In your function, write this

Regex.Replace(strIn, "[^\w\\-]", "")

This statement will replace any character that is not a word, \ or -. For e.g. aa-b@c will become aa-bc.

Upvotes: 6

Related Questions