1
$\begingroup$

I would like to replace lists within a list based on a string pattern with a blank sequence:

list = {{"", "abc"}, {"", "ooobc"}};  
rules = {{_, "abc"} -> "x", {_, ___~~ "bc"}->"y"};  
ReplaceAll[list, rules]
{"x", {"", _ ~~ "ooobc"}}

I would like to replace {"", "ooobc"} with "y". Since I tried from different angles - is there an elegant approach to use ReplaceAll with some kind of StringContainsQ logic?

Edit: One of the comments solves my problem well, so for completeness I add here:
rules = {{_, "abc"} -> "x", {_, _?(StringMatchQ[___ ~~ "bc"])} -> "y"};

$\endgroup$
  • $\begingroup$ What do you want to achieve? Does something like rules = {{_String, _?(StringMatchQ["abc", #] &)} -> "x"}; work for you? $\endgroup$ – Lukas Lang Sep 26 '17 at 19:02
  • $\begingroup$ I would like to replace based on a StringContains logic, i.e. if a String within any of the sublists contains "bc" as 2nd element, it should be replaced. $\endgroup$ – Patrick Bernhard Sep 26 '17 at 19:11
  • $\begingroup$ rules = {{_, "abc"} -> "x", {_, x_} /; StringContainsQ[x, "bc"] -> "y"}; like that? $\endgroup$ – N.J.Evans Sep 26 '17 at 19:17
  • 4
    $\begingroup$ Or, if you need something more general than StringContainsQ: rules = {{_, "abc"} -> "x", {_, _?(StringMatchQ[___ ~~ "bc"])} -> "y"}; $\endgroup$ – Lukas Lang Sep 26 '17 at 19:19
  • 2
    $\begingroup$ This applies here as well. $\endgroup$ – Szabolcs Sep 26 '17 at 20:31
1
$\begingroup$
condition = StringEndsQ["bc"];
rules = {{_, "abc"} -> "x", {_, _?condition} -> "y"};
(* or rules = {{_, "abc"} -> "x", {_, _?(StringEndsQ["bc"])} -> "y"}; *)

ReplaceAll[list, rules]

{"x", "y"}

You can also use StringMatchQ["*bc"] or StringContainsQ["bc"] in place of StringEndsQ["bc"].

Alternatively, you can use Condition (/;) instead of PatternTest (?) :

rules2 = {{_, "abc"} -> "x", {_, x_ /; condition[x]} -> "y"};

ReplaceAll[list, rules2]

{"x", "y"}

$\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.