2
$\begingroup$

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"

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

2 Answers 2

4
$\begingroup$

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.

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

StringDelete[str, PunctuationCharacter]

Result:

"This is my string number 5"

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.