Python (re)

Python Import Statement in PY

Match Python `import x` and `from x import y` statements, capturing the module and target.

Try it in the PY tester →

Pattern

regexPY
^(?:from\s+([\w.]+)\s+)?import\s+([\w.,\s\*]+?)(?:\s+as\s+\w+)?$   (flags: m)

Python (re) code

pyPython
import re

pattern = re.compile(r"^(?:from\s+([\w.]+)\s+)?import\s+([\w.,\s\*]+?)(?:\s+as\s+\w+)?$", re.MULTILINE)
input_text = "import os\nfrom collections import defaultdict"
for m in pattern.finditer(input_text):
    print(m.group(0))

Stdlib `re` module — no third-party dependency. Works on Python 3.6+.

How the pattern works

(?:from\s+([\w.]+)\s+)? optionally matches `from <module>` and captures the module path (group 1). import\s+ requires the import keyword. ([\w.,\s\*]+?) captures the imported names (lazy so the optional `as` alias doesn't get sucked in). (?:\s+as\s+\w+)? optionally matches an alias. The m flag lets ^/$ anchor per line in a multi-line file.

Examples

Input

import os\nfrom collections import defaultdict

Matches

  • import os
  • from collections import defaultdict

Input

from typing import List, Dict, Optional

Matches

  • from typing import List, Dict, Optional

Input

// not python

No match

Same pattern, other engines

← Back to Python Import Statement overview (all engines)