5
$\begingroup$

I have a nested list and would like to select a sub set of lists using a RegEx and I would prefer to use patterns (mainly for readability).

list = {
  {"1", "abc"},
  {"2", "abd"},
  {"3", "c"}
}

What I would like to use looks like:

Cases[list, {_, *Use a RegEx here for "ab"*}]

Actually, for my specific case substring matching would be sufficient. Any suggestions?

$\endgroup$
  • 1
    $\begingroup$ You need StringMatchQ[]: Cases[{{"1", "abc"}, {"2", "abd"}, {"3", "c"}}, {_, s_String /; StringMatchQ[s, RegularExpression["ab."]]}] $\endgroup$ – J. M. will be back soon Sep 25 '17 at 11:22
  • $\begingroup$ Works like charm. For my case even sufficient is: Cases[{{"1", "abc"}, {"2", "abd"}, {"3", "c"}},{_, s_String /; StringContainsQ[s, "ab"]}] $\endgroup$ – Dennis Sep 25 '17 at 11:26
  • $\begingroup$ Yes, that's indeed the shorter one (as well as Cases[{{"1", "abc"}, {"2", "abd"}, {"3", "c"}}, {_, s_String /; StringMatchQ[s, "ab*"]}]), but you did ask for regex... ;) $\endgroup$ – J. M. will be back soon Sep 25 '17 at 11:28
  • $\begingroup$ Hopefully not too stupid, but why {_, s_String /; "ab" ~~ ___} is not returning anything? $\endgroup$ – Dennis Sep 25 '17 at 11:53
  • 2
    $\begingroup$ Because you're mixing patterns with string patterns. That's why you confine the string patterns to string functions: Cases[{{"1", "abc"}, {"2", "abd"}, {"3", "c"}}, {_, s_String /; StringMatchQ[s, "ab" ~~ ___]}] $\endgroup$ – J. M. will be back soon Sep 25 '17 at 11:55
7
$\begingroup$

This is a good place to use the curried "operator form" of one of the string match predicates, such as:

Cases[list, {_, _?(StringMatchQ["ab*"])}]
(* {{"1", "abc"}, {"2", "abd"}} *)
$\endgroup$
  • 1
    $\begingroup$ I keep forgetting these curried forms; I was accustomed to not having them in older versions... :) $\endgroup$ – J. M. will be back soon Sep 25 '17 at 12:14

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.