如何在python中的字符串中搜索最后一次出现的正则表达式? [英] How to search for the last occurrence of a regular expression in a string in python?

查看:255
本文介绍了如何在python中的字符串中搜索最后一次出现的正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 python 中,我可以很容易地在这样的字符串中搜索第一次出现的正则表达式:

In python, I can easily search for the first occurrence of a regex within a string like this:

import re
re.search("pattern", "target_text")

现在我需要在字符串中找到最后一次出现的正则表达式,re 模块似乎不支持这一点.

Now I need to find the last occurrence of the regex in a string, this doesn't seems to be supported by re module.

我可以将字符串反转为搜索第一次出现",但我还需要反转正则表达式,这是一个更难的问题.

I can reverse the string to "search for the first occurrence", but I also need to reverse the regex, which is a much harder problem.

我也可以从左到右迭代查找所有出现的事件,只保留最后一个,但这看起来很尴尬.

I can also iterate to find all occurrences from left to right, and just keep the last one, but that looks awkward.

有没有一种聪明的方法来找到最右边的出现?

Is there a smart way to find the rightmost occurrence?

推荐答案

一种方法是在正则表达式前加上 (?s:.*) 并强制引擎在最远的位置尝试匹配并逐渐退缩:

One approach is to prefix the regex with (?s:.*) and force the engine to try matching at the furthest position and gradually backing off:

re.search("(?s:.*)pattern", "target_text")

请注意,此方法的结果可能与 re.findall("pattern", "target_text")[-1] 不同,因为 findall 方法搜索用于非重叠匹配,并且并非所有可以匹配的子字符串都包含在结果中.

Do note that the result of this method may differ from re.findall("pattern", "target_text")[-1], since the findall method searches for non-overlapping matches, and not all substrings which can be matched are included in the result.

例如,在 abaca 上执行正则表达式 aafindall 将返回 aba 作为唯一匹配项,并且选择它作为最后一个匹配项,而上面的代码将返回 aca 作为匹配项.

For example, executing the regex a.a on abaca, findall would return aba as the only match and select it as the last match, while the code above will return aca as the match.

另一种选择是使用 regex 包,它支持REVERSE 匹配模式.

Yet another alternative is to use regex package, which supports REVERSE matching mode.

结果或多或少与上述 re 包中带有 (?s:.*) 的方法相同.但是,由于我自己还没有尝试过这个包,所以不清楚在 REVERSE 模式下反向引用是如何工作的 - 在这种情况下,模式可能需要修改.

The result would be more or less the same as the method with (?s:.*) in re package as described above. However, since I haven't tried the package myself, it's not clear how backreference works in REVERSE mode - the pattern might require modification in such cases.

这篇关于如何在python中的字符串中搜索最后一次出现的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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