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:

It should not match:

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

3/8/2018 11:44:56 PM

Accepted Answer

For a regular expression, you would use:


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 ""

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 "", use the re.I option to the regular expression, or convert to a specific case (eg filename.lower()) before using string methods.

10/8/2008 11:48:59 PM


  • jobscry's answer ("^Run.?.py$") is incorrect (will not match "", for example).
  • orlandu63's answer ("/^Run[\w]*?.py$/") will not match "".

(I don't have enough reputation to comment, sorry.)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow