Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

People also ask

What matches the start of the string and what matches the end of the string in Python?

match(pattern, string, flags=0) method returns a match object if the regex matches at the beginning of the string. Read more in our blog tutorial. The re. fullmatch(pattern, string, flags=0) method returns a match object if the regex matches the whole string.

How do you check if a string starts with a certain character in Python?

The startswith() method returns True if a string starts with the specified prefix(string). If not, it returns False .

Which of following method is used to check if string is start with particular regex or not Startswith () Endswith () starts () none of above?

The startswith() string method checks whether a string starts with a particular substring. If the string starts with a specified substring, the startswith() method returns True; otherwise, the function returns False.

How do you match a pattern exactly at the beginning in Python?

match() function of re in Python will search the regular expression pattern and return the first occurrence. The Python RegEx Match method checks for a match only at the beginning of the string. So, if a match is found in the first line, it returns the match object.


I have a list of files, and I want to keep only the ones which start with 'test_' and end with '.py'. I want the regex to only return the text inside the 'test_' and '.py'. I do not want .pyc files included.

I have tried:

>>>filename = 'test_foo.py'
>>>re.search(r'(?<=test_).+(?=\.py)', filename).group()
foo.py

but it still returns the extension, and will allow '.pyc' extensions (which I do not want). I'm pretty sure it's the '+' which is consuming the whole string.

This works as a fallback, but I would prefer a regex solution:

>>>filename = 'test_foo.py'
>>>result = filename.startswith('test_') and filename.endswith('.py')
>>>result = result.replace('test_', '').replace('.py', '')
>>>print result
foo