regex - python regex:如何从某个单词到文本末尾的最小子字符串?
问题描述
我正在分析一个文本,我想提取从某个单词出现到文本结尾的最小子字符串。我的特殊问题是这个词可以在我的文本的几个部分中。
我尝试了以下方法:
pattern = re.compile('(word)(.*?)$', re.DOTALL)
result = re.search(pattern, MY_TEXT).group()
我的问题是,这不会导致返回尽可能小的字符串,而是在文本中找到最大的字符串(即:word
直到文本结尾的第一次出现,而不是最后一次出现)。我确信在第二个括号内添加?
字符.*
会解决问题,但事实并非如此。
示例输入:
text = "Pokémon is a media franchise managed by The Pokémon Company, a Japanese consortium between Nintendo, Game Freak, and Creatures.\nThe franchise began as Pokémon Red and Green (later released outside of Japan as Pokémon Red and Blue)."
word = 'Pokémon'
我希望我的结果是字符串:Pokémon Red and Blue).
,但现在我得到了整个文本。
我怎样才能得到我所期望的?提前致谢。
解决方案
您当前的模式(Pokémon)(.*?)$
有 2 个捕获组,它只会匹配第一次出现的 ,word
因为第二组随后匹配直到字符串的末尾。
要到达最后一个单词,您可以使用.*Pokémon
as .*
will first match 直到字符串的末尾,然后回溯直到它可以 fit Pokémon
。
然后字符串的其余部分将通过以下匹配.*
值在第一个捕获组中。
^.*(Pokémon .*)$
创建更动态的模式
text = "Pokémon is a media franchise managed by The Pokémon Company, a Japanese consortium between Nintendo, Game Freak, and Creatures.\nThe franchise began as Pokémon Red and Green (later released outside of Japan as Pokémon Red and Blue)."
word = "and"
pattern = r"^.*(" + re.escape(word) + ".*)$"
regex = re.compile(pattern, re.DOTALL)
result = re.search(regex, text).group(1)
print(result)
结果
和蓝色)。
如果这个词也可以是句子中的最后一个词,你可以断言右边的不是非空白字符(?!\S)
,使用否定的前瞻。
^.*(Pokémon(?!\S).*)$
推荐阅读
- javascript - QuerySelectorAll 不适用于 nth-child
- java - java纹理绘制等距投影
- android - 通过 USB 连接设备进行应用内计费测试
- r - 使用 dplyr 在 R 中将多列转换为双精度类型
- sql - 子查询中的 SQL 子查询
- python - Python Websocket Flutter 客户端
- docker - GitLab 容器注册表未更新 Docker 容器层
- go - 如何通过客户端获取 Kubernetes 节点的状态?
- javascript - 如何缩小 div 内的 iframe 以匹配其宽度?
- php - 如何在 Stripe 中一步创建客户、付款方式、订阅