Regular expression to match start of filename and filename extension

后端 未结 8 837
离开以前
离开以前 2020-12-08 15:35

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 s

相关标签:
8条回答
  • 2020-12-08 16:12

    If you write a slightly more complex regular expression, you can get an extra feature: extract the bit between "Run" and ".py":

    >>> import re
    >>> regex = '^Run(?P<name>.*)\.py$'
    >>> m = re.match(regex, 'RunFoo.py')
    >>> m.group('name')
    'Foo'
    

    (the extra bit is the parentheses and everything between them, except for '.*' which is as in Rob Howard's answer)

    0 讨论(0)
  • 2020-12-08 16:14

    This probably doesn't fully comply with file-naming standards, but here it goes:

    /^Run[\w]*?\.py$/
    
    0 讨论(0)
  • 2020-12-08 16:16

    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"]) )
    
    0 讨论(0)
  • 2020-12-08 16:16

    mabye:

    ^Run.*\.py$
    

    just a quick try

    0 讨论(0)
  • 2020-12-08 16:18

    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.

    0 讨论(0)
  • 2020-12-08 16:18

    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:

    import os
    for filename in os.listdir(dirname):
        root, ext = os.path.splitext(filename)
        if root.startswith('Run') and ext == '.py':
            print filename
    
    0 讨论(0)
提交回复
热议问题