Python Import Statement
Match Python `import x` and `from x import y` statements, capturing the module and target.
Try it in RegexPro →Available in
JavaScript / ECMAScript code
const re = new RegExp("^(?:from\\s+([\\w.]+)\\s+)?import\\s+([\\w.,\\s\\*]+?)(?:\\s+as\\s+\\w+)?$", "m");
const input = "import os\\nfrom collections import defaultdict";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
Python (re) code
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+.
Go (RE2) code
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(?m)^(?:from\s+([\w.]+)\s+)?import\s+([\w.,\s\*]+?)(?:\s+as\s+\w+)?$`)
input := `import os\nfrom collections import defaultdict`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
Pattern
^(?: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
Examples
Input
import os\nfrom collections import defaultdictMatches
import osfrom collections import defaultdict
Input
from typing import List, Dict, OptionalMatches
from typing import List, Dict, Optional
Input
// not pythonNo match
—Common use cases
- •Static analysis of Python source
- •Dependency graph generation
- •Auto-formatting tools (isort, ruff)
- •Migrating import styles in large codebases
Related patterns
Python f-String Expression
Text ProcessingMatch `{expression}` placeholders inside Python f-strings (or any single-brace template syntax).
Triple-Quoted String (Python / TS)
Text ProcessingMatch triple-quoted strings (Python docstrings, TypeScript triple-quote, etc.) including newlines.
SQL SELECT Statement
Text ProcessingMatch the column list and table name from a SQL SELECT ... FROM statement.
GraphQL Operation Header
Text ProcessingMatch GraphQL operation headers — `query`, `mutation`, or `subscription` — capturing the operation name.