# Delete everything but alphnumeric characters and spaces

This should have been asked here, but apparently it hasn't. How to delete everything from a string except alphanumeric characters and spaces? For example,

str = "This is, my string number 5!"


I want it to be "This is my string number 5"

• StringReplace["This is, my string number 5!", Except[LetterCharacter | DigitCharacter | " "] -> ""] gives the output you want (but doesn't have special characters). May 22 at 8:59

One way is to use RegularExpression

str = "This is, my string number 5!";
reg = RegularExpression["[A-Za-z0-9 ]"];
StringJoin[StringCases[str, reg]] // InputForm


gives

"This is my string number 5"


The " " is for any space, and A-Za-z0-9 stuff is for alpha numeric.

str = "This is, my string number 5!"
StringJoin@
StringCases[str
, (DigitCharacter | LetterCharacter | WhitespaceCharacter)
]


StringDelete[str, PunctuationCharacter]


Result:

"This is my string number 5"