匹配文件名开头和文件扩展名的正则表达式 [英] Regular expression to match start of filename and filename extension
问题描述
匹配以Run"开头且文件扩展名为.py"的字符串(在本例中为文件名)的正则表达式是什么?
What is the regular expression to match strings (in this case, file names) that start with 'Run' and have a filename extension of '.py'?
正则表达式应符合以下任一条件:
The regular expression should match any of the following:
RunFoo.py
RunBar.py
Run42.py
它不应该匹配:
myRunFoo.py
RunBar.py1
Run42.txt
我正在寻找的 SQL 等价物是 ... LIKE 'Run%.py' ...
.
The SQL equivalent of what I am looking for is ... LIKE 'Run%.py' ...
.
推荐答案
对于正则表达式,您可以使用:
For a regular expression, you would use:
re.match(r'Run.*\.py$')
简单解释:
- .表示匹配任何字符.
- * 表示匹配前一个字符的任何重复(因此 .* 表示任何字符序列)
- \ 是对显式点进行转义的转义
- $ 表示字符串的结尾",所以我们不匹配Run_foo.py.txt"
但是,对于此任务,您最好使用简单的字符串方法.即.
However, for this task, you're probably better off using simple string methods. ie.
filename.startswith("Run") and filename.endswith(".py")
注意:如果您想要不区分大小写(即匹配run.PY"以及Run.py",请使用正则表达式的 re.I 选项,或转换为特定大小写(例如 filename.lower()) 在使用字符串方法之前.
Note: if you want case insensitivity (ie. matching "run.PY" as well as "Run.py", use the re.I option to the regular expression, or convert to a specific case (eg filename.lower()) before using string methods.
这篇关于匹配文件名开头和文件扩展名的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!