1

Why is

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

"Xabcde"

and not

"abcde"

orome
  • 12,819
  • 3
  • 52
  • 100

2 Answers2

4

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}} *)
ciao
  • 25,774
  • 2
  • 58
  • 139
  • So that form of pattern will not work with /.? – orome Apr 04 '15 at 22:11
  • @raxacoricofallapatorius: Not for your intended result on strings... – ciao Apr 04 '15 at 22:12
  • Is there a pattern I can use with /. to get the result I'm looking for? – orome Apr 04 '15 at 22:14
  • @raxacoricofallapatorius: Perhaps you should fill in more details on what you're trying to accomplish in the OP? – ciao Apr 04 '15 at 22:16
  • Exactly that: Find a pattern to use with /. to achieve string pattern matching and replacement. – orome Apr 04 '15 at 22:18
  • @raxacoricofallapatorius: Again, that is what StringReplace is for - perhaps I'm being dense and not understanding your question - but see update, perhaps that's your intent? – ciao Apr 04 '15 at 22:22
  • Two intents really. I think you've addressed both. One was to see if there was a form that worked with /.. The other was to understand why my pattern wasn't working. I'm also curious how is have figured this out from the docs. – orome Apr 04 '15 at 22:26
  • @raxacoricofallapatorius: Groovy,+1 on question and thanks for accept. I suppose the tutorials and associated docs. under "pattern matching" is a good start - but yes, "figuring things out" from the documentation can sometimes be a bit treacherous. – ciao Apr 04 '15 at 22:28
  • Yeah. My takeaway from the docs is that a pattern is a pattern and should work everywhere it matches. (It's not just the docs of course but also the WL API design philosophy, which is based more on rigid — though not always consistent — rules rather than use cases.) – orome Apr 04 '15 at 22:32
0
"Xabcde" /. a_ :> StringCases[a, _] /. {"X", b__} :> StringJoin[b]
(*"abcde"*)
Basheer Algohi
  • 19,917
  • 1
  • 31
  • 78