$re = '/^(?:from\s+(\w+)(?:\.\w+)?\s+)?import\s+([^\s,.]+)(?:\.\w+)?/m';
$str = '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
';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php