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

Python greedy matching and multi-line matching

不言
不言Original
2018-04-19 10:29:482251browse

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!

Statement:
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