2
$\begingroup$

I'm trying to search in a list of strings those who match a pattern. But it seems that StringExpression in functions such as Position or Case won't work as in StringCase.

Cases[{"ABC", "DEF"}, StringExpression["DE", _]]

{}

StringCases["ABC DEF", StringExpression["DE", _]]

{DEF}

Why this happens?

$\endgroup$
2
  • 4
    $\begingroup$ Cases[{"ABC", "DEF"}, _String?(StringMatchQ[StringExpression["DE", _]])] or Cases[{"ABC", "DEF"}, _?(StringMatchQ[StringExpression["DE", _]])] ? $\endgroup$
    – kglr
    Aug 30, 2021 at 3:44
  • 3
    $\begingroup$ Documentation for StringExpression states: StringExpression objects can be used in many string manipulation functions, including StringReplace, StringCases, StringSplit, and StringMatchQ.. If you want to use it in other functions, use StringMatchQ with StringExpression as @kglr commented. $\endgroup$
    – Ben Izd
    Aug 30, 2021 at 3:45

1 Answer 1

6
$\begingroup$

Why this happens?

Because Cases expects an expression pattern and StringCases expects a string pattern.

With Case, write an expression pattern that invokes the string pattern matcher explicitly. Or better: use Select.

Select[{"ABC", "DEF"}, StringMatchQ["DE" ~~ _]]
(* {"DEF"} *)

Cases[{"ABC", "DEF"}, s_ /; StringMatchQ[s, "DE" ~~ _]]
(* {"DEF"} *)

See Select, Cases, StringMatchQ.

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