Python Import Statement in JS
Match Python `import x` and `from x import y` statements, capturing the module and target.
Try it in the JS tester →Pattern
regexJS
^(?:from\s+([\w.]+)\s+)?import\s+([\w.,\s\*]+?)(?:\s+as\s+\w+)?$ (flags: m)JavaScript / ECMAScript code
jsJavaScript
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).
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
—