Message Boards Message Boards

Can StringReplace[] be expressed as a rule ? How ?


The fomuli (1) and (2) with the function StringReplace[] to replace the string-expressions ended in "c" are normal. I try to convert them into the rules like (3) and (4) , but failed. What's wrong? (3) and (4) apparently are correct. How to rewrite (1) and (2) into the rules so as to follow "/." to replace a string expression ending in "c"?

StringReplace["abc abcb abdc", x_ ~~ "c" -> "0"]                     (*1*)
out[1]: "a0 a0b ab0"

StringReplace["abc abcb abdc abd", x__ ~~ "c" -> "1"]                (*2*)
out[2]: 1 abd

{"abc abcb abdc"} /. {x_ ~~ "c"} -> "0"                                   (*3*)
out[3]: {"abc abcb abdc"}

{"abc abcb abdc"} /. {x__ ~~ "c"} -> "1"                                  (*4*)
out[4]: {"abc abcb abdc"}
POSTED BY: Math Logic
2 months ago

Please make sure you know the rules:

The rules explain how to format your code properly. If you do not format code, it may become corrupted and useless to other members. Please EDIT your posts and make sure code blocks start on a new paragraph and look framed and colored like this.

int = Integrate[1/(x^3 - 1), x];
Map[Framed, int, Infinity]

enter image description here

POSTED BY: Moderation Team
2 months ago

It does not make sense to do this because ReplaceAll and StringReplace are different. In order to adapt ReplaceAll first you need to check if a pattern is a string and then apply StringReplace anyway.

So this will do:

 {"abc abcb abdc"} /. s_String :> StringReplace[s, {x_ ~~ "c"} -> "0"]

String patterns are a only a small part of pattern matching framwework:

p.s. you may be interested in an operator form of StringReplace:

 {"abc abcb abdc"} // StringReplace[{x_ ~~ "c"} -> "0"]

Notice it works with List ({}) here only because StringReplace is overloaded to thread over them. It will not work with arbitrary head:

foo["abc abcb abdc"] // StringReplace[{x_ ~~ "c"} -> "0"]
POSTED BY: Kuba Podkalicki
2 months ago

Your explanation is so wonderful !!!

POSTED BY: Math Logic
2 months ago

Group Abstract Group Abstract