I want to extract non-overlapping substrings from strings with only four possible characters a,b,c,d. These strings will always have equally many "a" and "d" characters. The substrings x I want satisy the following criteria:
- x starts with an "a" and ends with a "d", or is an "isolated" "b" or "c", see below.
- x has equally many "a"'s and "d"'s.
- Any substring of x starting at the first "a" has more "a"s than, or equally many "a"'s as, "d"'s.
For instance, the substrings I'm looking for in "abdcbaacdabbdd" are:
- "abd"
- "c"
- "b"
- "aacdabbdd"
I have made a working code doing this iteratively:
pick[i_]:=(Which[
occ[[i]]=="a",If[trigger++==0,startpos=i],
occ[[i]]=="d",If[--trigger==0,Sow[occ[[startpos;;i]]]],
trigger==0,Sow[{occ[[i]]}];
];
i+1);
subStrings[s_String]:=
Block[
{trigger=0,startpos,occ=Characters[s]},
Reap[Nest[pick,1,Length[occ]]][[2,1]]
]
but I would like to know if there is an easy way to do this using string patterns.