Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用正则表达式提取字符串的一部分_Python_Regex - Fatal编程技术网

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

Python 用正则表达式提取字符串的一部分,python,regex,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' 我意识到,在这种情

我试图从字符串中间提取两个字符。从字符串
['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]
,但我不想依赖前缀的长度保持不变。

它不应该只是

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

从外观上看,这相当整洁,尽管我没有使用python的正则表达式,所以我不确定它是否有怪癖/快捷方式。我假设您可以删除第一个捕获,并使用类似于
^\w+[.\u](\ w{2})
的东西作为正则表达式,以减少wordyThanks@rbev。我想我也可以摆脱
^\w+
,只需使用
re.search(r'[.\u](\ w{2}),str.group(1)