in reply to Extracting a substring according to some criteria

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

Replies are listed 'Best First'.
Re^2: Extracting a substring according to some criteria
by Benson (Initiate) on Oct 20, 2005 at 07:19 UTC
    Friends,

    I have encountered one problem for the below input because the last character G of first line and the first character C of the next line are @allowed region. But when I get the output, G and C are not in allowed. This is because There is a space after the last character G.

    my @allowed = qw[ AA AG GC GT CA CG TT TC ]; my $allowed = join "|", @allowed; my $regex = qr/ N+ | (?: (?=$allowed) . )* . /x; $data="TGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG +GGGGGGGGGGGGGGGGGGGGGATAG C"; print "$_\n" for $data =~ m/$regex/g;

    ie instead to be printed as GC I get it as

    G C
    which is wrong Please give a solution.

    Edit: g0n - code tags