Uncategorized

How to search multiple lines with Python? – IslandTropicaMan


Often you will want to search for words or phrase in the entire paragraph and here is the python regular expression code which will do that.


pattern = re.compile(r'^\w+ (\w+) (\w+)', re.M)

We use the re.M flag which will search the entire paragraph for the match words.

Now let us try out the program above…


gad = pattern.findall("hello mr Islandt\nhello mr gadgets")
print(gad)

…which will then display the following outcome


[('mr', 'Islandt'), ('mr', 'gadgets')]

Explanation :

The program above will look for two words in the first line and keeps them under a tuple and when the program meets the new line character it continues the search in the second line and return another tuple, both of the tuple will include inside a list. Using re.M flag the search will go on for multiple lines as long as there are more matches out there!





Source link

Leave a Reply

Your email address will not be published. Required fields are marked *