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 linebreaks from a regex match in python?

How can I make the bellow regex exclude matches that span across lines?

import re
reg = re.compile(r'\b(apple)(?:\W+\w+){0,4}?\W+(tree|plant|garden)')
reg.findall('my\napple tree in the garden')
reg.findall('apple\ntree in the garden')

The first one should match, the second one should not.
(Now both matches…)

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

>Solution :

Your \W matches newlines. To exclude them replace \W with [^\w\n]:

import re
reg = re.compile(r'\b(apple)(?:[^\n\w]+\w+){0,4}?[^\n\w]+(tree|plant|garden)')
print(reg.findall('my\napple tree in the garden'))
#  [('apple', 'tree')]
print(reg.findall('apple\ntree in the garden'))
#  []
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