Python Import Statement in GO
Match Python `import x` and `from x import y` statements, capturing the module and target.
Try it in the GO tester →Pattern
regexGO
^(?:from\s+([\w.]+)\s+)?import\s+([\w.,\s\*]+?)(?:\s+as\s+\w+)?$ (flags: m)Go (RE2) code
goGo
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.
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 defaultdictMatches
import osfrom collections import defaultdict
Input
from typing import List, Dict, OptionalMatches
from typing import List, Dict, Optional
Input
// not pythonNo match
—