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

How to exclude some text between two patterns?

I’d like to match all patterns between <PDF> and </PDF> inside a string:

import re

lines = """
hello
<PDF>
bla1
</PDF>
test
<PDF>
bla2
</PDF>
"""

matches = re.findall(r"<PDF>.*</PDF>", lines, re.DOTALL)
print(matches)

Output:

['<PDF>\nbla1\n</PDF>\ntest\n<PDF>\nbla2\n</PDF>']

Expected Output:

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

['<PDF>\nbla1\n</PDF>', '<PDF>\nbla2\n</PDF>']

What’s going wrong here? How can I ensure that no text between </PDF> and <PDF> gets matched?

>Solution :

* is greedy, so it tries to match as much as possible.

Use *? in this case. See Python’s documentation of module re:

Adding ? after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched.

matches = re.findall(r"<PDF>.*?</PDF>", lines, re.DOTALL)
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