在多行文字中查找模式

时间:2019-07-02 22:08:32

标签: regex python-3.x

我的文字相对较短,我想在其中找到一个简单的图案。这是我的文字:

US-born businessman John Adams, cmd of XYZ group conducting an aerial survey of flood effected districts of Houston.\n\nhe has announced $ 50 million donation for floodsrelief\n\n.

,我想获得“商人”和“捐赠”之间的所有文字。尽管它看起来很简单,但令人惊讶的是我的正则表达式无法检测到它:

import re
re.search(r'businessman.*donation',text)

任何解释和建议,我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

您可以简单地使用re.findallre.finditer尝试以下表达式:

businessman(.*?)donation

DEMO

测试

import re

regex = r"businessman(.*?)donation"

test_str = "US-born businessman John Adams, cmd of XYZ group conducting an aerial survey of flood effected districts of Houston.\\n\\nhe has announced $ 50 million donation for floodsrelief\\n\\n.
"

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))