python - 在python中的匹配对象中查找字符串

标签 python string find match

我想在 python 的“匹配对象”中找到一个字符串,但是“.find”不起作用。这是我的片段:

e_list = []
for file in os.listdir('.'):
    r = re.compile(r".*\.(aaa|bbb)$")
    e_found = r.search(file)
    if e_found is not None:
        e_list.append(e_found.group(0))

e_length = len(e_list);

for num_e in range(e_length):
    if(e_list[num_e].group(0).find('50M') > 0)
        print(e_list[num_e].group(0))

... 现在 e_list 就像:

[<_sre.SRE_Match object; span=(0, 7), match='30M.aaa'>,  
 <_sre.SRE_Match object; span=(0, 7), match='40M.bbb'>,  
 <_sre.SRE_Match object; span=(0, 7), match='50M.aaa'>,  
 <_sre.SRE_Match object; span=(0, 7), match='50M.bbb'>,  
 <_sre.SRE_Match object; span=(0, 7), match='50M.ccc'>]

我期望得到结果:

'50M.aaa'  
'50M.bbb'

e_list[0].group(0) 返回 '30M.aaa' 时,.find 无法应用,因为它是匹配项目的。那我该怎么办呢?

最佳答案

我认为 Python 不是您的第一语言,您的代码闻起来像 Java。

请不要使用re.compile,因为没有必要。只需使用 re.searchre.findall

在 Python 中,你可以使用:

result = re.findall('.*\.(aaa|bbb)$', file)

然后,result 是一个列表,您可以打印它或使用 for... 循环 来获取它的每一项。

您还可以使用:

result = re.search('.*\.(aaa|bbb)$', file)

结果是一组。

然后您应该使用result.group(1) 来获取匹配项。

所以,您的代码可以是:

e_list = []
for file in os.listdir('.'):
    e_found = re.search(".*\.(aaa|bbb)$", file)

    if e_found:
        e_list.append(e_found.group(1))


for item in e_list:
    if item.find('50M') > 0
        print(item)

关于python - 在python中的匹配对象中查找字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38908699/

相关文章:

python - 跳过 seaborn facetgrid 中的空面以​​进行注释

python - 从 R 到 python pandas : create id key series in order on duplicates

c++ - 如何从 C 风格的 const char* 数组中提取整数

java - 从多个输入字符串生成确定性唯一固定长度文件名字符串

linux - 如何压缩不符合特定条件的文件?

Python 命令不读取 .txt 文件

python 错误 - "IndexError: list index out of range"

javascript - 将关键字替换为 JavaScript 表达式

c++ - 在 vector<string> 中查找 vector<string> 元素很热门

jquery - 查找父元素的最快最有效的方法