1
$\begingroup$

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)?

$\endgroup$
  • $\begingroup$ @b.gatessucks Ah, you have to double click to select the full alphanumeric string, and I wasn't paying enough attention! $\endgroup$ – Bob2Alice Apr 1 '14 at 7:36
2
$\begingroup$
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 *)
$\endgroup$
  • $\begingroup$ This is terrific, thank you. $\endgroup$ – Bob2Alice Apr 1 '14 at 7:39
  • $\begingroup$ Also works with StringSplit. $\endgroup$ – b.gates.you.know.what Apr 1 '14 at 7:45
  • 1
    $\begingroup$ @b.gatessucks: Good idea- you should post as an answer, I think the more examples of different ways, the better. $\endgroup$ – ciao Apr 1 '14 at 7:46
2
$\begingroup$

Another way using RegularExpression

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

Gives:

 aa cja ajjcjjj c
$\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.