Home > Backend Development > Python Tutorial > Python greedy matching and multi-line matching

Python greedy matching and multi-line matching

不言
Release: 2018-04-19 10:29:48
Original
2255 people have browsed it

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']
Copy after login

Pay attention to compare this Situation:

>>> re.findall(r"a(\d+)b", "a23b")
  ['23']
>>> re.findall(r"a(\d+?)b", "a23b")
  ['23']
Copy after login

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')]
>>>
Copy after login

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']
Copy after login

However, if there is no ^ flag,

>>> re.findall(r"a(\d+)b", "a23b\na23b")
  ['23', '23']
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template