2

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.

alancalvitti
  • 15,143
  • 3
  • 27
  • 92

1 Answers1

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

Carl Woll
  • 130,679
  • 6
  • 243
  • 355
  • Is there a way to define a smarter version of Cases that applies StringMatchQ to StringExpression wherever these appear input expression? – alancalvitti Sep 03 '18 at 23:25