用正则表达式提取字符串的一部分

时间:2013-10-29 05:52:54

标签: python regex

我正在尝试从字符串中间提取两个字符。从字符串['data_EL27.dat', 'data.BV256.dat', 'data_BV257.dat'],我希望输出['EL', 'BV', 'BV']

以下是我使用正则表达式的内容,这对于这样一个简单的任务来说似乎过于笨重,我觉得我错过了一些更好的方法。

import re

str = 'data_EL27.dat'
m = re.search(r'(?:data[._])(\w{2})', str)
m.group(1) # 'EL'

我意识到在这种情况下我可以采用str[5:7],但我不想依赖前缀的长度保持不变。

1 个答案:

答案 0 :(得分:0)

不应该只是

m=re.search("data.(..)",str)