python regex从列表中只提取特定的模式文件名

amrnrhlw  于 2022-12-24  发布在  Python
关注(0)|答案(1)|浏览(121)

我想从列表中只提取某些文件。当从列表中只提取选定的文件时,我需要应用以下规则。
如果文件包含类似**f[1-99]t[1-99]v[1-99]f[1-9]_v[1-9]_t[1-9]**的组合的模式。下面是一些示例。

phone_football_androind_1_v1_te_t1_fe
phone_football_ios_v1_t1
foot_cricket2345678_f12_t4
tfd_fr_ve_t1_v1_f3_201234_yyymmmdd
def_000_t4_f1
file_job_1234567_f1_t55
ROKLOP_f33_t44
agdcv_t45
gop_gop_f1_t14_v14
file_op_v1_t1
fop_f1_v1_1223

你能不能帮助检查一下上面的模式是否包含在文件中,并且只取带有下面的模式的文件?我试过下面的,但是在python中用reges卡住了。不知道如何在regex中添加OR条件

import re

# Take input from users
MyString1 = "tfd_fr_ve_t1_v1_f3_201234_yyymmmdd"

# re.search() returns a Match object
# if there is a match anywhere in the string
if re.search('(_v(\d+)).*', MyString1):
    print("YES,it is present in string ")
else:
    print("NO,string is not present")
yebdmbv4

yebdmbv41#

要检查是否存在匹配项:

_[ftv][1-9]\d?(?!\d)
    • 说明**
  • _按字面匹配
  • [ftv]匹配ftv中的一个
  • [1-9]\d?匹配数字1 - 99
  • (?!\d)Assert右侧不是数字

Regex demo|Python demo
示例代码

import re

strings = [
    "tfd_fr_ve_t1_v1_f3_201234_yyymmmdd",
    "phone_football_androind_1_v1_te_t1_fe",
    "phone_football_ios_v1_t1",
    "foot_cricket2345678_f12_t4",
    "tfd_fr_ve_t1_v1_f3_201234_yyymmmdd",
    "def_000_t4_f1",
    "file_job_1234567_f1_t55",
    "ROKLOP_f33_t44",
    "agdcv_t45",
    "gop_gop_f1_t14_v14",
    "file_op_v1_t1",
    "fop_f1_v1_1223",
    "test"
]
pattern = r"_[ftv][1-9]\d?(?!\d)"
for s in strings:
    if re.search(pattern, s):
        print(f"YES, present in '{s}' ")
    else:
        print(f"NO, not present in '{s}'")

产出

YES, present in 'tfd_fr_ve_t1_v1_f3_201234_yyymmmdd' 
YES, present in 'phone_football_androind_1_v1_te_t1_fe' 
YES, present in 'phone_football_ios_v1_t1' 
YES, present in 'foot_cricket2345678_f12_t4' 
YES, present in 'tfd_fr_ve_t1_v1_f3_201234_yyymmmdd' 
YES, present in 'def_000_t4_f1' 
YES, present in 'file_job_1234567_f1_t55' 
YES, present in 'ROKLOP_f33_t44' 
YES, present in 'agdcv_t45' 
YES, present in 'gop_gop_f1_t14_v14' 
YES, present in 'file_op_v1_t1' 
YES, present in 'fop_f1_v1_1223' 
NO, not present in 'test'

相关问题