繁体   English   中英

Python re.search re.sub字符串

[英]Python re.search re.sub string

我有一个文件名,该文件名总是以数字开头,其文件扩展名为:

filename = 'photo_v_01_20415.jpg'

从其文件名中,我需要提取file_extension和文件扩展名itelf之前的最后一个数字。 由于分割的结果,我应该有两个字符串:

original_string = 'photo_v_01_20415.jpg'

string_result_01 = `photo_v_01_`  (first half of the file name)

string_result_02 = `20415.jpg`    (second half of the file name).

问题在于传入的文件名将不一致。 最后一个数字可以由下划线“ _”,空格“”,句号“”与其文件名分隔。 或其他任何东西。 可能的文件名示例:

photo_v_01_20415.jpg
photo_v_01.20415.jpg
photo_v_01 20415.jpg
photo_v_01____20415.jpg

看来我需要使用re。 具有re.search或re.sub。的表达式 任何建议,我将不胜感激!

import re

names = '''\
photo_v_01_20415.jpg
photo_v_01.20415.jpg
photo_v_01 20415.jpg
photo_v_01____20415.jpg'''.splitlines()

for name in names:
    prefix, suffix = re.match(r'(.+?[_. ])(\d+\.[^.]+)$', name).groups()
    print('{} --> {}\t{}'.format(name, prefix, suffix))

产量

photo_v_01_20415.jpg --> photo_v_01_    20415.jpg
photo_v_01.20415.jpg --> photo_v_01.    20415.jpg
photo_v_01 20415.jpg --> photo_v_01     20415.jpg
photo_v_01____20415.jpg --> photo_v_01____  20415.jpg

正则表达式模式r'(.+?[_. ])(\\d+\\.[^.]+)$'表示

r'             define a raw string
(              with first group
     .+?           non-greedily match 1-or-more of any character
     [_. ]         followed by a literal underscore, period or space
)              end first group 
(              followed by second group
     \d+           1-or-more digits in [0-9]
     \.            literal period
     [^.]+         1-or-more of anything but a period
)              end second group 
$              match the end of the string
'              end raw string

使用re.match而不是re.search将所有字符串匹配到模式。 从而

import re

def split_name(filename):
    match = re.match(r'(.*?)(\d+\.[^.]+)', filename)
    if match:
        return match.groups()
    else:
        return None, None

for name in [ 'foo123.jpg', 'bar;)234.png', 'baz^_^456.JPEG', 'notanumber.bmp' ]:
    prefix, suffix = split_name(name)
    print("prefix = %r, suffix = %r" % (prefix, suffix))

印刷品:

prefix = 'foo', suffix = '123.jpg'
prefix = 'bar;)', suffix = '234.png'
prefix = 'baz^_^', suffix = '456.JPEG'
prefix = None, suffix = None

适用于任意后缀; 如果文件名与模式不匹配,则匹配失败,并返回None,None。

import re

matcher = re.compile('(.*[._ ])(\d+.jpg)')
result = matcher.match(filename)

根据需要将其他选项添加到[._]。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM