Home > Article > Backend Development > Python greedy matching and multi-line matching
The following is an example explanation of greedy matching and multi-line matching in python. It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together
1 Non-greedy flag
>>> re.findall(r"a(\d+?)", "a23b") ['2'] >>> re.findall(r"a(\d+)", "a23b") ['23']
Pay attention to compare this Situation:
>>> re.findall(r"a(\d+)b", "a23b") ['23'] >>> re.findall(r"a(\d+?)b", "a23b") ['23']
2 If you want to match multiple lines, add the re.S and re.M flags
re.S:. Will match newline characters. Default. Will not match newline characters.
>>> re.findall(r"a(\d+)b.+a(\d+)b", "a23b\na34b") [] >>> re.findall(r"a(\d+)b.+a(\d+)b", "a23b\na34b", re.S) [('23', '34')] >>>
re.M: ^ The $ flag will match every line. By default ^ and $ will only match the first line
>>> re.findall(r"^a(\d+)b", "a23b\na34b") ['23'] >>> re.findall(r"^a(\d+)b", "a23b\na34b", re.M) ['23', '34']
However, if there is no ^ flag,
>>> re.findall(r"a(\d+)b", "a23b\na23b") ['23', '23']
Related recommendations:
Write a simple web crawler in Python to capture videos
The above is the detailed content of Python greedy matching and multi-line matching. For more information, please follow other related articles on the PHP Chinese website!