簡體   English   中英

Python - 正則表達式搜索以給定文本開頭和結尾的字符串

[英]Python - regex search for string which starts and ends with the given text

我有一個文件列表,我想只保留以'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

問題是你的模式匹配test_之前和.py之前的任何字符串,但這並不限制它在test_之前或.py之后有其他字符。

你需要使用start( ^ )和end( $錨點 另外,別忘了逃避. 字符。 試試這種模式:

(?<=^test_).+(?=\.py$)

看這個:

import re

files = [
"test_1.py",
"Test.py",
"test.pyc",
"test.py",
"script.py"]

print [x for x in files if re.search("^test_.*py$", x)]

輸出:

['test_1.py']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM