Is there a clean way to match patterns that combine general patterns and ?StringExpression

For example, Cases will not match any parts in this construction:

{{"my Foo", 1}, {"my Bar", "a"}, {"your Foo", "b"}, {"your Bar", 4}} // Cases[{"my" ~~ __, _Integer}]


Of course StringCases can be used on the string expression parts but then

{{"my Foo", 1}, {"my Bar", "a"}, {"your Foo", "b"}, {"your Bar", 4}} // 
  Map[First] // StringCases["my" ~~ __]

{{"my Foo"}, {"my Bar"}, {}, {}}

This seems a very basic question, I'd be surprised if it hasn't been asked before but didn't find anything with a cursory search.


1 Answer 1


You can use Condition and StringMatchQ:

    {"my Foo",1},{"my Bar","a"},{"your Foo","b"},{"your Bar",4}
} //Cases[{s_ /; StringMatchQ[s,"my"~~__], _Integer}]

{{"my Foo", 1}}

  • $\begingroup$ Is there a way to define a smarter version of Cases that applies StringMatchQ to StringExpression wherever these appear input expression? $\endgroup$ Sep 3, 2018 at 23:25

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.