正则表达式解析python中的导入语句 [英] regex to parse import statements in python

查看:26
本文介绍了正则表达式解析python中的导入语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我编写单个正则表达式以从 python 源代码行获取模块吗?

can someone help me writing single regex to get module(s) from python source line?

from abc.lmn import pqr
from abc.lmn import pqr as xyz
import abc
import abc as xyz

里面有3个子部分

[from(\s)<module>(\s)] --> get module if this part exist
import(\s)<module>     --> get module
[(\s)as(\s)<alias>]    --> ignore if this part exist

类似的东西

:?[from(\s)<module>(\s)]import(\s)<module>:?[(\s)as(\s)<alias>]

推荐答案

看起来您可以将 from 设为可选,而 import
同时忽略as.

Looks like you could make the from optional and the import required at
the same time ignoring the as.

(?m)^(?:from[ ]+(\S+)[ ]+)?import[ ]+(\S+)[ ]*$

https://regex101.com/r/fmoAuh/1

说明

 (?m)                          # Modifiers: multi-line
 ^                             # Beginning of line
 (?:                           # Optional from
      from [ ]+ 
      ( \S+ )                       # (1), from <module>
      [ ]+ 
 )?

 import [ ]+                   # Required import
 ( \S+ )                       # (2), import <module>
 [ ]* 
 $                             # End of line

<小时>

或者,如果您想匹配 as 但不想捕获任何内容,请使用它.


Or, if you want to match the as but do not want to capture anything, use this.

(?m)^(?:from[ ]+(\S+)[ ]+)?import[ ]+(\S+)(?:[ ]+as[ ]+\S+)?[]*$

https://regex101.com/r/xFtey5/1

扩展

 (?m)                          # Modifiers: multi-line
 ^                             # Beginning of line
 (?:                           # Optional from
      from [ ]+ 
      ( \S+ )                       # (1), from <module>
      [ ]+ 
 )?

 import [ ]+                   # Required import
 ( \S+ )                       # (2), import <module>

 (?:                           # Optional as
      [ ]+ 
      as [ ]+ 
      \S+                          # <alias>
 )?
 [ ]* 
 $ 

这篇关于正则表达式解析python中的导入语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆