Text Processingflags: m

Python Import Statement

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

Try it in RegexPro →

Available in

Pattern

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

Raw source: ^(?:from\s+([\w.]+)\s+)?import\s+([\w.,\s\*]+?)(?:\s+as\s+\w+)?$

How it 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

Common use cases

  • Static analysis of Python source
  • Dependency graph generation
  • Auto-formatting tools (isort, ruff)
  • Migrating import styles in large codebases