python - 正则表达式在 Pythex 上运行良好,但在 Python 上运行不佳

标签 python regex

我在pythex上使用了下面的正则表达式来测试它:

(\d|t)(_\d+){1}\.

它运行良好,我主要对第 2 组感兴趣。它成功运行如下所示:

pythex demo

但是,我无法让 Python 实际向我显示正确的结果。这是一个 MWE:

fn_list = ['IMG_0064.png',
           'IMG_0064.JPG',
           'IMG_0064_1.JPG',
           'IMG_0064_2.JPG',
           'IMG_0064_2.PNG',
           'IMG_0064_2.BMP',
           'IMG_0064_3.JPEG',
           'IMG_0065.JPG',
           'IMG_0065.JPEG',
           'IMG-20150623-00176-preview-left.jpg',
           'IMG-20150623-00176-preview-left_2.jpg',
           'thumb_2595.bmp',
           'thumb_2595_1.bmp',
           'thumb_2595_15.bmp']

pattern = re.compile(r'(\d|t)(_\d+){1}\.', re.IGNORECASE)

for line in fn_list:
    search_obj = re.match(pattern, line)
    if search_obj:
        matching_group = search_obj.groups()
        print matching_group

没有输出。

但是,上面的 pythex 清楚地显示了为每个返回的两个组,第二个应该存在并击中更多文件。我做错了什么?

最佳答案

您需要使用 re.search(),而不是 re.match()re.search() 匹配字符串中的任何位置,而 re.match() 仅匹配开头。

import re

fn_list = ['IMG_0064.png',
           'IMG_0064.JPG',
           'IMG_0064_1.JPG',
           'IMG_0064_2.JPG',
           'IMG_0064_2.PNG',
           'IMG_0064_2.BMP',
           'IMG_0064_3.JPEG',
           'IMG_0065.JPG',
           'IMG_0065.JPEG',
           'IMG-20150623-00176-preview-left.jpg',
           'IMG-20150623-00176-preview-left_2.jpg',
           'thumb_2595.bmp',
           'thumb_2595_1.bmp',
           'thumb_2595_15.bmp']

pattern = re.compile(r'(\d|t)(_\d+){1}\.', re.IGNORECASE)

for line in fn_list:
    search_obj = re.search(pattern, line)  # CHANGED HERE
    if search_obj:
        matching_group = search_obj.groups()
        print matching_group

结果:

('4', '_1')
('4', '_2')
('4', '_2')
('4', '_2')
('4', '_3')
('t', '_2')
('5', '_1')
('5', '_15')

由于您正在编译正则表达式,因此您可以执行 search_obj = pattern.search(line) 而不是 search_obj = re.search(pattern, line)。至于您的正则表达式本身,r'([\dt])(_\d+)\.' 等同于您正在使用的正则表达式,并且更简洁一些。

关于python - 正则表达式在 Pythex 上运行良好,但在 Python 上运行不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31975921/

相关文章:

python - Pandas 数据框的箱线图

python - 连接 mysql wamp 和 django 时出现问题?

php - 奇怪的 PHP 字符串错误

java - 使用带有非空白正则表达式的 String split() 方法

python - 使用 matplotlib 将 y 范围更改为从 0 开始

Python 二维条件

python - "List object not callable"

html 模式 ="[A-Za-z]{50}"表示有效输入无效

java - 从 html 行中提取 href 的正确正则表达式是什么? ( java )

java - 用于匹配字符串中分隔符内的任何字符的正则表达式