# How do I find and highlight the elements of a list that match a specific pattern?

I have a list of positive and negative ones {1,1,-1,1,1,-1,1,-1,1,-1,-1,1,1,1,-1} And I want to find and highlight the subsequence of the lists that have the pattern {...,1,1,___,-1,-1,...}. So ideally my output would be {1,1,-1,1,1,-1,1,-1,1,-1,-1,1,1,1,-1}.

• related: 95912 – Kuba Jan 28 '17 at 22:02

list = {1, 1, -1, 1, 1, -1, 1, -1, 1, -1, -1, 1, 1, 1, -1};

SequenceCases[list, {a___, Shortest[b : PatternSequence[1, 1, ___, -1, -1]],  c__} :>
Flatten[{a, Style[#, Bold, Red] & /@ {b}, c}]][[1]]


Note: the subsequence starting with the first entry also satisfies your pattern, and it can be obtained by removingShortest above or by changing it to Longest:

SequenceCases[list, {a___, b : PatternSequence[1, 1, ___, -1, -1],  c__} :>
Flatten[{a, Style[#, Bold, Red] & /@ {b}, c}]][[1]]


• Is there a way to find the first time that pattern occurs? The code is taking a really long time to run with your solution, and I think finding the first occurrence might still give me what I need. – xanadu Jan 28 '17 at 23:23
• @xanadu, using the third argument SequenceCases[list, {a___, b : PatternSequence[1, 1, ___, -1, -1], c__} :> Flatten[{a, Style[#, Bold, Red] & /@ {b}, c}], n] gives the first n matches. – kglr Jan 28 '17 at 23:53