如何获得非贪婪和贪婪之间所有可能匹配的列表 [英] How can I get a list of all possible matches in between non-greedy and greedy

查看:105
本文介绍了如何获得非贪婪和贪婪之间所有可能匹配的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中有字符串"I like lettuce and carrots and onions".

I have the string "I like lettuce and carrots and onions" in Python.

我以为我可以通过使用像.* and这样的正则表达式来获得以下匹配["I like lettuce", "I like lettuce and carrots", "I like lettuce and carrots and onions"]. (正则表达式应匹配和"之前的任何字符.)

I thought I could get the following matches ["I like lettuce", "I like lettuce and carrots", "I like lettuce and carrots and onions"] by using a regex like .* and. (The regex should match any character up to " and".)

但是,使用贪婪版本(.* and)仅给我最后一个匹配项,而使用非贪婪版本(.*? and)仅给我第一个匹配项.

However, using the greedy version (.* and) gives me only the last match, and using the non-greedy version (.*? and) gives me only the first match.

我怎么能获得全部三场比赛?

How can I get all three matches?

(我不需要正则表达式解决方案.)

(I do not need a regex solution.)

推荐答案

为了娱乐,请在Python 3中使用字符串partition方法.它将在字符串中搜索子字符串,并返回3元组.有比赛时,就是

For fun, use the string partition method in Python 3. It searches a string for a substring, and returns a 3-tuple. When there's a match, it's

(比赛之前的字符串,比赛,比赛之后的字符串)

(string before the match, the match, string after the match)

一旦习惯了,它会非常令人愉悦-无需索引,并且很容易获得正确的结果.因此,尽管此代码比其他方法更长,但您应该能够轻松地对此进行推理:

Once you're used to it, it's very pleasant - no indexing needed, and it makes it easy to get the right results. So while this code is longer than some other ways, you should be able to reason about it easily:

def findallprefix(s, sep):
    sofar = ""
    while True:
        head, matched, s = s.partition(sep)
        if matched:
            assert matched == sep
            sofar += head
            yield sofar
            sofar += matched
        else:
            break

s = "I like lettuce and carrots and onions and dressing."
for match in findallprefix(s, " and"):
    print(repr(match))

可打印

'I like lettuce'
'I like lettuce and carrots'
'I like lettuce and carrots and onions'

这篇关于如何获得非贪婪和贪婪之间所有可能匹配的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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