← retour aux snippets

re: capturer en multi-lignes sans gourmandise

Utiliser DOTALL et quantificateurs non-gourmands pour matcher proprement.

python regex #regex#re#multiline

objectif

Utiliser DOTALL et quantificateurs non-gourmands pour matcher proprement.

code minimal

import re
s = "BEGIN\nline1\nline2\nEND\nBEGIN\nline3\nEND"
pat = re.compile(r"BEGIN\n(.*?)\nEND", re.DOTALL)
matches = pat.findall(s)
print(matches[0].split("\n")[0])  # attendu: line1

utilisation

import re
print(bool(re.search(r"a.+?c", "abcabc")))  # non-gourmand trouve 'abc'

variante(s) utile(s)

import re
txt = "id=42, id=7"
print(re.findall(r"id=(\d+)", txt) == ["42","7"])

notes

  • DOTALL (re.S) fait matcher ’.’ sur les retours à la ligne.
  • Préférez des motifs précis et non-gourmands pour éviter l’explosion.