简体   繁体   中英

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)

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM