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 "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.Answer #2 100 %
I don't really understand why you're after a regular expression to solve this 'problem'. You're just after a way to find all .py files that start with 'Run'. So this is a simple solution that will work, without resorting to compiling an running a regular expression:
Answer #3 100 %
import os for filename in os.listdir(dirname): root, ext = os.path.splitext(filename) if root.startswith('Run') and ext == '.py': print filename
- jobscry's answer ("^Run.?.py$") is incorrect (will not match "Run123.py", for example).
- orlandu63's answer ("/^Run[\w]*?.py$/") will not match "RunFoo.Bar.py".
(I don't have enough reputation to comment, sorry.)Answer #4 100 %
Or, in python specifically:
import re re.match(r"^Run.*\.py$", stringtocheck)
This will match "Runfoobar.py", but not "runfoobar.PY". To make it case insensitive, instead use:
Answer #5 100 %
re.match(r"^Run.*\.py$", stringtocheck, re.I)
You don't need a regular expression, you can use glob, which takes wildcards e.g. Run*.py
For example, to get those files in your current directory...
import os, glob files = glob.glob( "".join([ os.getcwd(), "\\Run*.py"]) )