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$
6
  • 1
    $\begingroup$ You need StringMatchQ[]: Cases[{{"1", "abc"}, {"2", "abd"}, {"3", "c"}}, {_, s_String /; StringMatchQ[s, RegularExpression["ab."]]}] $\endgroup$ Sep 25, 2017 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$ Sep 25, 2017 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$ Sep 25, 2017 at 11:28
  • $\begingroup$ Hopefully not too stupid, but why {_, s_String /; "ab" ~~ ___} is not returning anything? $\endgroup$ Sep 25, 2017 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$ Sep 25, 2017 at 11:55

1 Answer 1

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
  • 1
    $\begingroup$ I keep forgetting these curried forms; I was accustomed to not having them in older versions... :) $\endgroup$ Sep 25, 2017 at 12:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.