Home > other >  Cannot pattern match patterns ending with specific characters
Cannot pattern match patterns ending with specific characters

Time:07-22

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)

CodePudding user response:

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']

CodePudding user response:

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']

CodePudding user response:

You can try this

import re
a ="foo bar baz\nbar foo baz\nbaz foo bar\nbar baz foo\nfoo baz bar\nbaz 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 baz\nbar foo baz\nbaz foo bar\nbar baz foo\nfoo baz bar\nbaz bar foo"
search = re.findall("(. bar)\n", a)
print(search)

Output:

['baz foo bar', 'foo baz bar']
  • Related