Finding and printing a specific Pattern in a given string
<p>I am writing a code find a specific pattern in a given string using python or perl. I had some success in finding the pattern using C but python or perl usage is mandatory for this assignment and I am very new in both of these lanuages.</p>

<p>My string looks like this (Amino acid sequence) :-</p>

<pre><code> MKTSGNQDEILVIRKGWLTINNIGIMKGGSKEYWFVLTAENLSWYKDDEEKEKKYMLSVDNLKLRDVEKGFMSSKHIFAL
</code></pre>

<p>The pattern I want to find is </p>

<pre><code> KXXXXXX(K\R)XR 
</code></pre>

<p>Please note that Letters between K and K\R are not fixed. However, there is only letter between K\R and R. So, in the given string my pattern is like this and exist between letter no. 54 to 65 (if I counted correctly) based on "smallest pattern" search :-</p>

<pre><code>  KYMLSVDNLKLR
</code></pre>

<p>Previously, I was using C if-else condition to break this given string and printed out word count (not fully successful).</p>

<pre><code>   printf(%c, word[i]);
     if ((word [i] == 'K' || word [i] == 'R' )) &amp;&amp; word [i+2] == 'R') {
        printf("\n");
        printf("%d\n",i);
    }
</code></pre>

<p>I agree It dint capture everything. If anyone can help me help me solving this problem, that would be great.</p>

<p>You say you want the match to be non-greedy, but that doesn't make sense. I think you are trying to find the minimal match. If so, that's very hard to do. This is the regex match you need:</p>

<pre><code>/
    K
    (?: (?: [^KR] | R(?!.R) )+
    |   .
    )
    [KR]
    .
    R
/sx
</code></pre>

<hr>

<p>However, it wouldn't surprise me if there's a bug. The only sure way to find a minimal match is to find all possible matches.</p>

<pre><code>my $match;
while (/(?= ( K.+[KR].R ) )/sxg) {
    if (!defined($match) || length($1) &gt; length($match)) {
        $match = $1;
    }
}
</code></pre>

<p>But this will be far slower, especially for long strings.</p>

python perl