Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python re findall() returns only the first match

Given a list of references, I want to split each of those.

[1] Some text, and some more
and even some more
[2] Some more text 

I want to get each of those references as a list of strings like below:

['[1] Some text, and some more\n and even some more', '[2] Some more text ']

When I do it on https://regex101.com/r/YPWt9Z/1, it marks all the matches correctly. But when I do the same in python, I only get the first match:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

with open('ref.txt', 'r') as file:
    data=file.read()
lines = re.findall(r'^\[[^\[]*', data)
for x in lines:
    print(x)  #x just prints the first match, not all

How do I get all the matches?

>Solution :

To have findall() match each line in the string separately, you need to call it with a flag:

lines = re.findall(r'^\[[^\[]*', data, re.MULTILINE)

Alternatively use re.split():

lines = re.split(r'\n(\[\d+\])')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading