1
$\begingroup$

Why is

"Xabcde" /. "X" ~~ e__ -> e

"Xabcde"

and not

"abcde"

$\endgroup$
1

2 Answers 2

4
$\begingroup$

Use

StringReplace["Xabcde", "X" ~~ e__ -> e].

Replace, et al are for lists/expressions...

Notice that AtomQ@"Xabcde" is True, so regular (non-string) replace operations only "see" it as a singular entity:

"Xabcde" /. "Xabcde" -> 1

(* 1 *)

From the docs for ReplaceAll: "... to transform each subpart..." - but there is no "subpart" for atoms, so regular replace operations only operate on the string as a complete entity.

If you want to do such things as part of a larger replacement program, something like this can be done:

test = {"Xabcde", {1, 2, 3}};

test /. {a_String :> StringReplace[a, "X" ~~ e__ -> e], {a_, b_, c_} :> {b, c}}

(* {"abcde", {2,3}} *)
$\endgroup$
9
  • $\begingroup$ So that form of pattern will not work with /.? $\endgroup$ Commented Apr 4, 2015 at 22:11
  • $\begingroup$ @raxacoricofallapatorius: Not for your intended result on strings... $\endgroup$ Commented Apr 4, 2015 at 22:12
  • $\begingroup$ Is there a pattern I can use with /. to get the result I'm looking for? $\endgroup$ Commented Apr 4, 2015 at 22:14
  • $\begingroup$ @raxacoricofallapatorius: Perhaps you should fill in more details on what you're trying to accomplish in the OP? $\endgroup$ Commented Apr 4, 2015 at 22:16
  • $\begingroup$ Exactly that: Find a pattern to use with /. to achieve string pattern matching and replacement. $\endgroup$ Commented Apr 4, 2015 at 22:18
0
$\begingroup$
"Xabcde" /. a_ :> StringCases[a, _] /. {"X", b__} :> StringJoin[b]
(*"abcde"*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.