Here's how to do it with a regex. You inch along the string, and if the next two characters are allowed, then keep matching. As soon as the next two characters aren't allowed, take one more character and stop. (BTW, you don't need to explicitly list @disallowed if it is the complement of @allowed).
my @allowed = qw[ AA AG GC GT CA CG TT TC ]; my $allowed = join "|", @allowed; my $regex = qr/ N+ | (?: (?=$allowed) . )* . /x; my $data = "CTGTCAGCNNNCCGGTTTTCAAGNNGAGCACACACCAAAAATGCACCAAAGCTTNACA +TCCATACAAA"; print "$_\n" for $data =~ m/$regex/g;
The regex also has to match /N+/ sequences, so that is added as a special case (Update: Adding "NN" to @allowed would also have the same effect).

This doesn't work for multi-line data. You can either first remove all the newlines from the data, or if you don't want to have the whole file in memory at once, you can do this "inching along" process manually. Take one character at a time, keeping track of the last one you've seen as well. If the last two characters are an allowed sequence, then add the new character to a buffer. If the last two characters are disallowed, then print the buffer (it is a maximal allowed string), and restart the buffer starting with this new character.

Update: Something like this:

my @allowed = qw[ AA AG GC GT CA CG TT TC NN ]; my %allowed = map { $_ => 1 } @allowed; my $buf; while ( get next input character as $c ) { if ($allowed{ substr($buf,-1).$c }) { $buf .= $c; } else { print "$buf\n"; $buf = $c; } } print "$buf\n"; # don't forget last one

blokhead


In reply to Re: Extracting a substring according to some criteria by blokhead
in thread Extracting a substring according to some criteria by Benson

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.