使用python正则表达式查找最后一个匹配项 [英] Find last match with python regular expression

查看:187
本文介绍了使用python正则表达式查找最后一个匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想匹配字符串中最后一次出现的简单模式,例如

list = re.findall(r"\w+ AAAA \w+", "foo bar AAAA foo2 AAAA bar2")打印最后一场比赛:",列表[len(list)-1]

但是,如果字符串,则会生成一个巨大的匹配列表.有没有更直接的方法来匹配第二次出现的"AAAA ",还是应该使用这种解决方法?

解决方案

你可以使用 $ 表示行尾字符:

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

另外,请注意 list 对你的变量来说是一个不好的名字,因为它隐藏了内置类型.要访问列表的最后一个元素,您可以使用 [-1] 索引:

<预><代码>>>>lst = [2, 3, 4]>>>lst[-1]4

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 "last match: ", list[len(list)-1]

However, if the string is very long, a huge list of matches is generated. Is there a more direct way to match the second occurrence of " AAAA ", or should I use this workaround?

解决方案

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

这篇关于使用python正则表达式查找最后一个匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆