Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot pattern match patterns ending with specific characters

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading