0

Does replacing a list of strings have to be this convoluted (with a warning too)? Why can't ReplaceAll natively use string matching patterns?

s = {"dir abc", "wfori", "dir ej99", "lkdwk", "pokp"};

s /. {x_ /; StringMatchQ[x, "dir " ~~ ___] -> "X"} s /. {"dir " ~~ ___ -> "X"}

(* {"X", "wfori", "X", "lkdwk", "pokp"} ) ( {"dir abc", "wfori", "dir ej99", "lkdwk", "pokp"} *)

I know there's StringReplace but then, it hasn't the "built-in" ability to remove an element like ReplaceAll does

s /. {x_ /; StringMatchQ[x, "dir " ~~ ___] -> Nothing}
StringReplace[{"dir abc", "wfori", "dir ej99", "lkdwk", "pokp"}, "dir " ~~ ___ -> Nothing]

(* {"wfori", "lkdwk", "pokp"} ) ( {StringExpression[Nothing], "wfori", StringExpression[Nothing], "lkdwk", "pokp"} *)

Domenico Modica
  • 489
  • 2
  • 9
  • 2
    Select[StringFreeQ["dir"]][s] – Syed Dec 07 '22 at 11:25
  • @Syed thanks, there are many workarounds, but is not about a particular solution, I'd like to understand better if ReplaceAll can't work at all... For anything other but strings I could use ReplaceAll both for actual replacing or "delete" something from a list and this capability is much powerful than relying on two different methods to replace/delete strings in a list... Does it have to be this way? – Domenico Modica Dec 07 '22 at 11:46
  • 2
    StringReplace only works on strings. If you make the pattern more restrictive by replacing x_ with x_String then you get no warning. – Gustavo Delfino Dec 07 '22 at 12:49
  • 1
    There was a similar question about why there is a distinction between general patterns and string patterns in Specifying string patterns in DeleteCases. – WReach Dec 07 '22 at 14:57
  • @WReach thanks it's exactly the answer I was looking for – Domenico Modica Dec 08 '22 at 07:50

0 Answers0