python 中用于搜索文件的正则表达式
regular expressions in python for searching file
我想知道如何获取符合此类型的文件:
recording_i.file_extension
例如:
recording_1.mp4
recording_112.mp4
recording_11.mov
我有一个正则表达式:
(recording_\d*)(\..*)
我的正则表达式无法正常工作。
与我的类型不匹配的错误文件名:lalala_recording_1.mp4, recording_.mp4
但是我的 re 用于这个例子,但是我的代码应该 return [] 这个例子。
你能修复我的正则表达式吗?
谢谢
使用
(^recording_\d+)(\.\w{3}$)
测试
import re
s = """recording_1.mp4
recording_112.mp4
recording_11.mov
lalala_recording_1.mp4,
recording_.mp4"""
pattern = re.compile(r"(^recording_\d+)(\.\w{3}$)")
for l in s.split():
if pattern.match(l):
print(l)
输出(仅需要的文件)
recording_1.mp4
recording_112.mp4
recording_11.mov
说明
With r"(^recording_\d+)(\.\w{3}$)"--1)
- use \d+ since need at least one number
- \w{3} for three letter suffix
- ^ to ensure starts with recording
- $ to ensure ends after suffix
特定后缀
import re
# List of suffixes to match
suffixes_list = ['mp4', 'mov']
suffixes = '|'.join(suffixes_list)
# Use suffixes in pattern (rather than excepting
# any 3 letter word
pattern = re.compile(fr"(^recording_\d+)(\.{suffixes}$)")
测试
s = """recording_1.mp4
recording_112.mp4
recording_11.mov
lalala_recording_1.mp4,
recording_.mp4
dummy1.exe
dummy2.pdf
dummy3.exe"""
for l in s.split():
if pattern.match(l):
print(l)
输出
recording_1.mp4
recording_112.mp4
recording_11.mov
我想知道如何获取符合此类型的文件:
recording_i.file_extension
例如:
recording_1.mp4
recording_112.mp4
recording_11.mov
我有一个正则表达式:
(recording_\d*)(\..*)
我的正则表达式无法正常工作。
与我的类型不匹配的错误文件名:lalala_recording_1.mp4, recording_.mp4
但是我的 re 用于这个例子,但是我的代码应该 return [] 这个例子。
你能修复我的正则表达式吗?
谢谢
使用
(^recording_\d+)(\.\w{3}$)
测试
import re
s = """recording_1.mp4
recording_112.mp4
recording_11.mov
lalala_recording_1.mp4,
recording_.mp4"""
pattern = re.compile(r"(^recording_\d+)(\.\w{3}$)")
for l in s.split():
if pattern.match(l):
print(l)
输出(仅需要的文件)
recording_1.mp4
recording_112.mp4
recording_11.mov
说明
With r"(^recording_\d+)(\.\w{3}$)"--1)
- use \d+ since need at least one number
- \w{3} for three letter suffix
- ^ to ensure starts with recording
- $ to ensure ends after suffix
特定后缀
import re
# List of suffixes to match
suffixes_list = ['mp4', 'mov']
suffixes = '|'.join(suffixes_list)
# Use suffixes in pattern (rather than excepting
# any 3 letter word
pattern = re.compile(fr"(^recording_\d+)(\.{suffixes}$)")
测试
s = """recording_1.mp4
recording_112.mp4
recording_11.mov
lalala_recording_1.mp4,
recording_.mp4
dummy1.exe
dummy2.pdf
dummy3.exe"""
for l in s.split():
if pattern.match(l):
print(l)
输出
recording_1.mp4
recording_112.mp4
recording_11.mov