I’m trying to match all patterns that end in bar.
This is my regex pattern ".*bar$".
I get no result… same thing happens if I use the carrot in to match at the beginning of patterns.
string = """
foo bar baz
bar foo baz
baz foo bar
bar baz foo
foo baz bar
baz bar foo
"""
search = re.findall(".*bar$", string)
for i in search:
print(i)
>Solution :
Your pattern works if you set the re.MULTILINE flag. That way your pattern is matched on a line-by-line basis, so the $ matches line endings in addition to the ending of the string as a whole.
# Result: ['baz foo bar', 'foo baz bar']
search = re.findall(".*bar$", string, flags=re.MULTILINE)
Edit: Looks like you just want everything that ends in bar, regardless of line endings. In that case, you can tell set the star * to be non-greedy by adding a ?:
>>> re.findall(".*?bar", "danibarsambarbreadbar")
['danibar', 'sambar', 'breadbar']