Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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 at 7:36

2 Answers 2

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 at 7:39
    
Also works with StringSplit. –  b.gatessucks Apr 1 at 7:45
1  
@b.gatessucks: Good idea- you should post as an answer, I think the more examples of different ways, the better. –  rasher Apr 1 at 7:46

Another way using RegularExpression

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

Gives:

 aa cja ajjcjjj c
share|improve this answer

Your Answer

 
discard

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.