2013-09-25 39 views
0

我总是对一些结束与它的文件扩展名出发,如文件名:Python的re.search应用re.sub串

filename = 'photo_v_01_20415.jpg' 

从它的文件名,我需要提取FILE_EXTENSION,最后一个数字它位于文件扩展名itslelf之前。由于分割,我应该有两个字符串:

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。我会很感激任何建议!

回答

3

使用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 

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

3
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 
+1

谢谢!你们好棒! – alphanumeric

+0

我已经使用Antti Haapala解决方案的部分更正了我的答案;向Antti Haapala道歉,我无法忍受我的回答错误。我会留下我的回答主要是因为它解释了正则表达式的含义。 – unutbu

0
import re 

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

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

+0

这个解决方案效果很好:prefix,suffix = re.search(r'(。+?[_。])(\ d + .jpg)$',seq_name).groups()但是文件扩展名不会总是' JPG”。我怎么能调整这个表达式,使其对于任何非JPG格式的文件都有效? – alphanumeric