Not getting required output using findall in python
<p>Earlier ,I could not put the exact question.My apologies.</p>

<p>Below is what I am looking for :</p>

<p>I am reading a string from file as below  and there can be  multiple such kind of strings in the file.</p>

<pre><code>" VEGETABLE    1
    POTATOE_PRODUCE    1.1    1SIMLA(INDIA)
    BANANA   1.2    A_BRAZIL(OR INDIA)
    CARROT_PRODUCE 1.3 A_BRAZIL/AFRICA"
</code></pre>

<p>I want to capture the entire string as output using findall only.</p>

<p><strong>My script:</strong></p>

<pre><code>import re
import string

f=open('log.txt')
contents = f.read()
output=re.findall('(VEGETABLE.*)(\s+\w+\s+.*)+',contents)
print output
</code></pre>

<p>Above script is giving output as </p>

<p>[('VEGETABLE    1', '\n     CARROT_PRODUCE 1.3 A_BRAZIL/AFRICA')]</p>

<p>But contents in between are missing.</p>

<p>Solution in last snippet in this answer.</p>

<pre><code>&gt;&gt;&gt; import re
&gt;&gt;&gt; str2='d1 talk walk joke'

&gt;&gt;&gt; re.findall('(\d\s+)(\w+\s)+',str2) 
[('1 ', 'walk ')] 
</code></pre>

<p>output is a list with only one occurrence of the given pattern. The tuple in the list contains two strings that matched corresponding two groupings given within () in the pattern  </p>

<h1>Experiment 1</h1>

<p>Removed the last '+' which made pattern to select the first match instead of greedy last match</p>

<pre><code>&gt;&gt;&gt; re.findall('(\d\s+)(\w+\s)',str2) 
[('1 ', 'talk ')] 
</code></pre>

<h1>Experiment 2</h1>

<p>Added one more group to find the third words followed with one or more spaces. But if the sting has more than 3 words followed by spaces, this will still find only three words.</p>

<pre><code>&gt;&gt;&gt; re.findall('(\d\s+)(\w+\s)(\w+\s)',str2) 
[('1 ', 'talk ', 'walk ')] # 
</code></pre>

<h1>Experiment 3</h1>

<p>Using '|' to match the pattern multipel times. Note the tuple has disappeared. Also note that the first match is not containing only the number. This may be because \w is superset of \d</p>

<pre><code>&gt;&gt;&gt; re.findall('\d\s+|\w+\s+',str2) 
['d1 ', 'talk ', 'walk ']
</code></pre>

<h1>Final Experiment</h1>

<pre><code>&gt;&gt;&gt; re.findall('\d\s+|[a-z]+\s+',str2)
['1 ', 'talk ', 'walk ']
</code></pre>

<p>Hope this helps.</p>

python regex findall