Python - regex search for string which starts and ends with the given text -
i have list of files, , want keep ones start 'test_' , end '.py'. want regex return text inside 'test_' , '.py'. not want .pyc files included.
i have tried:
>>>filename = 'test_foo.py' >>>re.search(r'(?<=test_).+(?=\.py)', filename).group() foo.py but still returns extension, , allow '.pyc' extensions (which not want). i'm pretty sure it's '+' consuming whole string.
this works fallback, prefer regex solution:
>>>filename = 'test_foo.py' >>>result = filename.startswith('test_') , filename.endswith('.py') >>>result = result.replace('test_', '').replace('.py', '') >>>print result foo
the problem pattern matches string comes after test_ , before .py, doesn't restrict having other characters before test_ or after .py.
you need use start (^) , end ($) anchors. also, don't forget escape . character. try pattern:
(?<=^test_).+(?=\.py$)
Comments
Post a Comment