I have a list of possible Python import statements and I need to parse them in JavaScript. I found this post regex to parse import statements in python and adopted it for JavaScript but for some reason, not all the statements are parsed.
Here is the test:
const re = /^(?:from[ ]+(\S+)[ ]+)?import[ ]+(\S+)(?:[ ]+as[ ]+\S+)?[ ]*$/g;
const lines = ['import numpy as np',
'import pandas as pd',
'import pkg.mod1, pkg.mod2',
'from pkg.mod2 import Bar as Qux',
'from abc.lmn import pqr',
'from abc.lmn import pqr as xyz',
'import mod',
'from mod import s, foo',
'from mod import *',
'from pkg.mod3 import *',
'from mod import s as string, a as alist',
'import re, json'];
for (var i = 0; i < lines.length; i++){
const res = re.exec(lines[i]);
console.log(res);
}
Ideally, the code would extract the names of packages that need to be loaded (not modules) but it's okay if it would work at least on all the examples.
Ideal expected result:
- 'numpy',
- 'pandas',
- 'pkg',
- 'pkg',
- 'abc',
- 'abc',
- 'mod',
- 'mod',
- 'mod',
- 'pkg',
- 'mod'
- ['re', 'json']