Message Boards Message Boards

GROUPS:

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

Posted 1 year ago
1079 Views
|
3 Replies
|
4 Total Likes
|

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"}
3 Replies

Please make sure you know the rules: https://wolfr.am/READ-1ST

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

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:

http://reference.wolfram.com/language/tutorial/Introduction-Patterns.html http://reference.wolfram.com/language/tutorial/StringPatterns.html

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 1 year ago

Your explanation is so wonderful !!!

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract