重复捕获组将仅捕获最后一次迭代。这就是为什么您需要重组您的正则表达式以使用 re.findall。
\s*
(?:
(?:^from\s+
( # Base (from (base) import ...)
(?:[a-zA-Z_][a-zA-Z_0-9]* # Variable name
(?:\.[a-zA-Z_][a-zA-Z_0-9]*)* # Attribute (.attr)
)
)\s+import\s+
)
|
(?:^import\s|,)\s*
)
( # Name of imported module (import (this))
(?:[a-zA-Z_][a-zA-Z_0-9]* # Variable name
(?:\.[a-zA-Z_][a-zA-Z_0-9]*)* # Attribute (.attr)
)
)
(?:
\s+as\s+
( # Variable module is imported into (import foo as bar)
(?:[a-zA-Z_][a-zA-Z_0-9]* # Variable name
(?:\.[a-zA-Z_][a-zA-Z_0-9]*)* # Attribute (.attr)
)
)
)?
\s*
(?=,|$) # Ensure there is another thing being imported or it is the end of string
Try it on regex101.com
捕获组 0 将是 Base,捕获组 1 将是(您所追求的)导入模块的名称,捕获组 2 将是模块所在的变量 (from (group 0) import (group 1) as (group 2))
import re
regex = r"\s*(?:(?:^from\s+((?:[a-zA-Z_][a-zA-Z_0-9]*(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*))\s+import\s+)|(?:^import\s|,)\s*)((?:[a-zA-Z_][a-zA-Z_0-9]*(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*))(?:\s+as\s+((?:[a-zA-Z_][a-zA-Z_0-9]*(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*)))?\s*(?=,|$)"
print(re.findall(regex, "import pandas, os, sys"))
[('', 'pandas', ''), ('', 'os', ''), ('', 'sys', '')]
如果你不关心其他两个捕获组,你可以删除它们。