Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

python - Regular expression to match start of filename and filename extension

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

It should not match:

myRunFoo.py
RunBar.py1
Run42.txt

The SQL equivalent of what I am looking for is ... LIKE 'Run%.py' ....

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For a regular expression, you would use:

re.match(r'Run.*.py$')

A quick explanation:

  • . means match any character.
  • * means match any repetition of the previous character (hence .* means any sequence of chars)
  • is an escape to escape the explicit dot
  • $ indicates "end of the string", so we don't match "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")

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...