A ragged array of strings with a mix of sublists is processed to output some sublists and not others.

The sublists to output have a date, data, and information; in no particular order.

The information strings have no identifiable pattern.

Using Select or StringCases the individual data strings that match are output.

The complete sublist containing the dates, data and information is to be output. Other than a "For" type loop is there a function that will "select" or "pick" the sublists that contain the wanted data and output the entire sublist. It would also be nice not to have to use the DeleteCases to delete occurrences of {} produced by non-matches output by Select and StringCases.

Example data:

(records={{"date1","junk11","junk12","junk13"}, {"date2","junk21","junk22"},
  {"date3","junk31","junk32","junk33","junk34"}, {"date4","aa","data41","bb","ccccc"},
  {"date5","junk51","junk52"}, {"date6","cc","data61","d","ee","fff"},
  {"date7","junk71","junk72","junk73"}, {"date8","data81","g123"}})//Column

Select and StringCases code and results:

DeleteCases[Select[#, StringMatchQ["data" ~~ ___]] & /@ records, {}]
DeleteCases[Flatten@StringCases[#, "data" ~~ ___] & /@ records, {}]



Desired output:


2 Answers 2

Select[MatchQ[{___, _?(StringMatchQ["data" ~~ ___]), ___}]] @ records
{{"date4", "aa", "data41", "bb", "ccccc"},   
 {"date6", "cc", "data61", "d", "ee", "fff"},   
 {"date8", "data81", "g123"}}
Cases[records, {___, _?(StringMatchQ["data" ~~ ___]), ___}, All]
{{"date4", "aa", "data41", "bb", "ccccc"},   
 {"date6", "cc", "data61", "d", "ee", "fff"},   
 {"date8", "data81", "g123"}}

First create tests for the data and date entries:

pdate[x_] := StringMatchQ[x, RegularExpression["date\\d++"]]; 
pdata[x_] := StringMatchQ[x, RegularExpression["data\\d++"]];

Then you need a function that applies these tests to your sublists:

((Or @@ pdate[#]) && (Or @@ pdata[#])) &

This function can now be used in Select to pick the sublists you want:

Select[records, ((Or @@ pdate[#]) && (Or @@ pdata[#])) &]

{{"date4", "aa", "data41", "bb", "ccccc"}, {"date6", "cc", "data61", 
  "d", "ee", "fff"}, {"date8", "data81", "g123"}}

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.