Not getting required output using findall in python
Question: Earlier ,I could not put the exact question.My apologies.

Below is what I am looking for :

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

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

I want to capture the entire string as output using findall only.

**My script:**

    
    
    import re
    import string
    
    f=open('log.txt')
    contents = f.read()
    output=re.findall('(VEGETABLE.*)(\s+\w+\s+.*)+',contents)
    print output
    

Above script is giving output as

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

But contents in between are missing.


Answer: Solution in last snippet in this answer.

    
    
    >>> import re
    >>> str2='d1 talk walk joke'
    
    >>> re.findall('(\d\s+)(\w+\s)+',str2) 
    [('1 ', 'walk ')] 
    

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

# Experiment 1

Removed the last '+' which made pattern to select the first match instead of
greedy last match

    
    
    >>> re.findall('(\d\s+)(\w+\s)',str2) 
    [('1 ', 'talk ')] 
    

# Experiment 2

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.

    
    
    >>> re.findall('(\d\s+)(\w+\s)(\w+\s)',str2) 
    [('1 ', 'talk ', 'walk ')] # 
    

# Experiment 3

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

    
    
    >>> re.findall('\d\s+|\w+\s+',str2) 
    ['d1 ', 'talk ', 'walk ']
    

# Final Experiment

    
    
    >>> re.findall('\d\s+|[a-z]+\s+',str2)
    ['1 ', 'talk ', 'walk ']
    

Hope this helps.

