python - Match package name(s) using regex
问题描述
I have Python import statements that I want to match using regex.
I have these four types of strings,
- import collections as c
I want to match just the last word 'c'. => import collections as c
- from datetime import date as dt
I want to match just the last word 'dt'. => from datetime import date as dt
- from sys import stdout, stderr, stdin
I want to match everything after import. => from sys import stdout, stderr, stdin
- import re
I want to match just the last word 're' => import re
Currently I am using inbuit way to split by "import" and get the string after that which seems inefficient.
I tried doing this,
(?<=import ).*
but it just matches case 3 and case 4, it doesn't match case 1 and case 2.
How do I do this using regex?
解决方案
This works for your four cases, and I believe it should be mostly general:
re.search('import( \S* as)? (.*)$',your_string)[2]
briefly, you search for all the words that come at the end (which is basically what you always want) after 'import'
, but you want XXX as
to be excluded in case these follow the word import
so you put that as an optional match (in parentheses). Finally, you select your second matching item. Hope this is clear
推荐阅读
- javascript - Powerbi在javascriptfile中嵌入设置是否有效?
- oracle - Ora-00257 归档程序错误。仅连接内部。直到被释放
- php - 生成一个随机字符串,每 24 小时刷新一次?
- c# - c# .Net Worker 服务中的测试用例方法
- javascript - 将鼠标悬停在文本上以在固定位置显示图像
- c - 在 C/C++ 中将结构的动态数组传递给 fun
- clickhouse - 如何在 ClickHouse 中附加多个分区?
- javascript - 正则表达式仅替换字符串中的一些 / 字符
- ruby-on-rails - Rails - 创建对象的新实例时搜索/显示可用选项
- sql - SQL subselect 语句在某些机器上非常慢