簡體   English   中英

Python正則表達式匹配字符串模式並返回子字符串

[英]Python regular expression to match a string pattern and return the sub string

我有許多名稱如下的文件:

<some name>_2536by1632.jpg
<some name1>_4800by2304.JPG
<some name2>_904by904.jpg

因此,名稱部分各不相同,擴展名始終為jpg,但也可以大寫。 x和y在<x>by<y>可能有有限的值,我以這種格式列出這些值:

possible_sizes = [ (2536,1632), (4800,2304), ...]

我需要測試文件名是否為這種模式,如果是,則需要返回<x>by<y>字符串的值。

截至目前,我無需使用正則表達式即可執行此操作。 像這樣:

for item in possible_sizes:
    if "_{0}by{1}.jpg".format(item[0],item[1]) in filename.lower():
        dimension = "{0}by{1}".format(item[0],item[1])

但這不是一個很干凈的解決方案,特別是當將來可能增加的尺寸值時。

如何使用正則表達式呢?

您可以只使用Python的字符串方法:

import os

# O(1) lookup time
possible_sizes = frozenset([(2536, 1632), (4800, 2304), ...])

name, extension = os.path.splitext(filename)
title, size = filename.rsplit('_')
width, height = map(int, size.split('by'))

if (width, height) in possible_sizes:
    print(width, height)

可能不是最明智的選擇,但應該易於閱讀。

字符串:

  1. 可以以任何^.*開頭
  2. 必須有下划線_
  3. 后跟一個數字(至少由1個數字組成) \\d+
  4. 其次是“通過” by
  5. 后跟一個數字(至少由1個數字組成) \\d+
  6. 以.jpg或。結尾的 JPG \\.(jpg|JPG)$

(?P<X> ....) makes a match accessible by the name X.

Leads to this expression "^.*_((?P<X>\\d+)by(?P<Y>\\d+))\\.(jpg|JPG)$"

示例程序:

import re

possible_sizes = [ ( 2536, 1632 ), ( 4800, 2304 )]
names = ["<some name>_2536by1632.jpg", "<some name1>_4800by2304.JPG", "<some name2>_904by904.jpg"]
pattern = "^.*_((?P<X>\d+)by(?P<Y>\d+))\.(jpg|JPG)$"

for name in names:
    matchobj = re.match( pattern, name )
    if matchobj:
        if ( int( matchobj.group( "X" ) ), int( matchobj.group( "Y" ) ) ) in possible_sizes:
            print matchobj.group( 1 )

Output

2536by1632

4800by2304

這與您提出問題的實質無關,但我認為這實際上是可行的-

possible_sizes = { "_2536by1632.jpg" : (2536,1632), "_4800by2304.jpg" : (4800,2304)}
for filename in filenames:
    if filename.endswith in possible_sizes:
        return possible_sizes[filename]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM