Find last match with python regular expression

前端 未结 5 997
北荒
北荒 2020-12-05 17:20

I want to match the last occurrence of a simple pattern in a string, e.g.

list = re.findall(r\"\\w+ AAAA \\w+\", \"foo bar AAAA foo2 AAAA bar2\")
print \"las         


        
5条回答
  •  [愿得一人]
    2020-12-05 18:03

    you could use $ that denotes end of the line character:

    >>> s = """foo bar AAAA
    foo2 AAAA bar2"""
    >>> re.findall(r"\w+ AAAA \w+$", s)
    ['foo2 AAAA bar2']
    

    Also, note that list is a bad name for your variable, as it shadows built-in type. To access the last element of a list you could just use [-1] index:

    >>> lst = [2, 3, 4]
    >>> lst[-1]
    4
    

提交回复
热议问题