Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Say I have a string {100 aa bbc%j%b%wa ajjcj11j0%2wj fc} with a lot of undesired characters or spaces in it, for example: {" ", "%", "w", "j"}. I'd like to strip the string of these characters, with the provided example giving us the output string:

testString = "100 aa bbc%j%b%wa ajjcj11j0%2wj fc";
StringReplace[testString, {" ", "%", "w", "j"} -> ""]

out: "100aabbcbaac1102fc";

Now, say we don't have a convenient list of undesired characters / spaces / paragraph indicators / etc. Is there a way to select for certain characters instead of specifying that certain characters should be deleted (as in the example)?

share|improve this question
@b.gatessucks Ah, you have to double click to select the full alphanumeric string, and I wasn't paying enough attention! – Bob2Alice Apr 1 '14 at 7:36
up vote 2 down vote accepted
testString = "100 aa bbc%j%b%wa ajjcj11j0%2wj fc";
StringJoin@StringCases[testString, {"a", "j", "c", " "}]

(* aa cja ajjcjjj c *)

The second argument for StringCases can use character ranges, etc.

As to "bulk" but specific upcase/downcase, something like:

StringReplace[%, (# -> ToUpperCase[#]) & /@ {"c", "j"}]

(*  aa CJa aJJCJJJ C *)
share|improve this answer
This is terrific, thank you. – Bob2Alice Apr 1 '14 at 7:39
Also works with StringSplit. – b.gatessucks Apr 1 '14 at 7:45
@b.gatessucks: Good idea- you should post as an answer, I think the more examples of different ways, the better. – ciao Apr 1 '14 at 7:46

Another way using RegularExpression

StringReplace[testString, RegularExpression["[^ajc ]"] :> ""]


 aa cja ajjcjjj c
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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