Cannot pattern match patterns ending with specific characters

Question:

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)
Asked By: bananatoast

||

Answers:

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']
Answered By: fsimonjetz

You can try this

import re
a ="foo bar baznbar foo baznbaz foo barnbar baz foonfoo baz barnbaz bar foo"
search = re.finditer("(.+bar)n", a)
for i in search:
    print(i.group())

Output:

baz foo bar

foo baz bar

Or you can try This:

import re
a ="foo bar baznbar foo baznbaz foo barnbar baz foonfoo baz barnbaz bar foo"
search = re.findall("(.+bar)n", a)
print(search)

Output:

['baz foo bar', 'foo baz bar']
Answered By: Hiral Talsaniya

Try this:

string = """
foo bar baz
bar foo baz
baz foo bar
bar baz foo
foo baz bar
baz bar foo
"""
re.findall(r"(.+bar)n", string)

output:

['baz foo bar', 'foo baz bar']
Answered By: bpfrd
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.