I have a list of strings list. I am trying to get rid of some elements that match string pattern patt:
list /. x_ /; StringMatchQ[x, patt] -> Nothing
I get the result I want but I also get an error:
StringMatchQ::strse: String or list of strings expected at position 1 in StringMatchQ[List, patt].
This happens because ReplaceAll also evaluates the condition on the Head of list. How can I get the result I want but prevent the error?
Answer
IMHO the simplest solution is to restrict the pattern on the left side of Condition, i.e. change x_ to x_String:
patt = ___ ~~ "a" ~~ ___;
{"good", "bad"} /. x_String /; StringMatchQ[x, patt] -> Sequence[]
(* {"good"} *)
You can instead use Replace as indicated in other answers, however:
- the optimal levelspec to target atomic elements like Strings is
{-1} - The default
HeadsvalueFalseis what preventsListfrom being pattern matched.
Please understand that Replace does not work the same as ReplaceAll, regardless of levelspec, because it uses a different traversal order. See:
Comments
Post a Comment