12

These are valid characters:

a-z
A-Z
0-9
-
/ 

How do I remove all other characters from my string?

Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
Sriram
  • 121
  • 1
  • 1
  • 3
  • 3
    Which characters aren't special? Do you want the cleaned string to only contain `-` and `/` or do you want to keep other characters too? – LukeH Sep 13 '10 at 13:51
  • a-zA-Z0-9 and -,/ rest all not needed but mainly right now i need to remove crlf,cr,lf using vb.net – Sriram Sep 13 '10 at 13:57

5 Answers5

27
Dim cleanString As String = Regex.Replace(yourString, "[^A-Za-z0-9\-/]", "")
LukeH
  • 263,068
  • 57
  • 365
  • 409
  • Little support requesting.. If I need to exclude a special character from this. Not special character, say If I want white space and # symbol not to be replaced.. how can I modify this.. – Sandeep Thomas Sep 14 '17 at 12:01
  • @sforsandeep: Just add them into the group, for example: `[^A-Za-z0-9\-/#\s]` or similar. – LukeH Sep 15 '17 at 11:31
6

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.

Sidharth Panwar
  • 4,606
  • 6
  • 27
  • 36
  • 1
    +1 The OP probably wants to keep spaces as well - though maybe not tabs (?) which would be `Regex.Replace(strIn, "[^\w\\- ]", "")` – El Ronnoco Sep 13 '10 at 14:20
  • Watch out! The `\w` class doesn't only match alphanumerics. For example, your regex won't correctly clean *"a_string_containing_underscores"*. (Also, the OP wants to allow forward-slashes, not backslashes.) – LukeH Sep 13 '10 at 14:26
  • Hmm. Slash should be different. – Sidharth Panwar Sep 13 '10 at 16:36
1
Dim txt As String
txt = Regex.Replace(txt, "[^a-zA-Z 0-9-/-]", "")
But Jao
  • 21
  • 1
  • 4
0
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
0

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.

Mr.B
  • 3,484
  • 2
  • 26
  • 40