1

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"};

kglr
  • 394,356
  • 18
  • 477
  • 896
Patrick Bernhard
  • 707
  • 5
  • 12

1 Answers1

1
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"}

kglr
  • 394,356
  • 18
  • 477
  • 896