我在一个目录中有几千个文件,我想做的是:
示例:
34291.daveabc2712144.txt
eidddvabc24156.mp3
beonabcsimple.csv
输出:
abc27121
abc24156
abcsimpl
向您致谢
杰克
>>> s = '34291.daveabc2712144.txt'
>>> s[(start := s.index('abc')): start + 8]
'abc27121'
假设可以找到'abc'
,并且需要Python3.8+用于walrus运算符。
在我看来,这样简单的任务不需要正则表达式。
可以使用正则表达式:
abc.{5}
在Python
中:
import re
strings = ["34291.daveabc2712144.txt", "eidddvabc24156.mp3", "beonabcsimple.csv"]
rx = re.compile(r'abc.{5}')
names = [m.group(0) for string in strings for m in [rx.search(string)] if m]
print(names)
请参阅regex101.com上的演示。
您可以使用regex执行如下操作:
import re
txts = ["34291.daveabc2712144.txt",
"eidddvabc24156.mp3",
"beonabcsimple.csv",
"fABCgfdge.txt"]
for i in txts:
x = re.findall("abc.{5}", i)
#if you need to be case insensitive you can do this
#x = re.findall("abc.{5}", i, re.IGNORECASE)
if x:
print(x)