How to use regular expressions (preferably in Python) to extract the value of "3" using only "A" in the expression. Each value is on a new line.

I try as follows, but does not work:

text = """ A ab 1 2 bc 3 4 B ab 5 6 bc 7 8 """ re_result = re.search('A.*bc\n+(\d)', text, re.S) print(re_result.group(1)) 

Throws 7, not 3.

    1 answer 1

    Use lazy search by adding ? :

     re_result = re.search('A.*?bc\n+(\d)', text, re.S) 

    Because you have a few bc and greedy search, then the regular has reached the last bc and honestly pulled out the next number - 7 .

    Example:

    • .* is greedy. He will try to find as much as possible.
    • .*? - this is lazy. He will stop at the first coincidence.