我有一个文件列表,我只想保留以“test_”开头并以“.py”结尾的文件。我希望正则表达式只返回“test_”和“.py”中的文本。我不希望包含 .pyc 文件。
我努力了:
>>>filename = 'test_foo.py'
>>>re.search(r'(?<=test_).+(?=\.py)', filename).group()
foo.py
但它仍然返回扩展名,并允许“.pyc”扩展名(我不想要)。我很确定是 '+' 消耗了整个字符串。
这可以作为后备,但我更喜欢正则表达式解决方案:
>>>filename = 'test_foo.py'
>>>result = filename.startswith('test_') and filename.endswith('.py')
>>>result = result.replace('test_', '').replace('.py', '')
>>>print result
foo