首页 > 解决方案 > 如何使用正则表达式在 Python 中获取段落中的最后一个单词

问题描述

我正在寻找一种方法来提取一行中的最后一个单词。我只想提取名字:Mike 我的代码是

import re

text_to_search = '''
I like Apples and bananas 
I like fruits and yogurt
thisUser: Your name : Mike Lewis
Email: mike@mail.com
type: Fullresopnse
'''
pattern = re.compile(r'thisUser: Your name :\s[A-Z]\w+')

matches = pattern.search(text_to_search)

print(matches)

运行此代码让我:

re.Match object; span=(54, 80), match='thisUser: Your name : Mike'

我如何获取"Mike""Mike lewis"打印?

标签: pythonregex

解决方案


这个表达式有一个返回 Mike 的捕获组:

thisUser:\s*Your name\s*:\s*(\S+)

演示

测试

import re

regex = r"thisUser:\s*Your name\s*:\s*(\S+)"

test_str = ("I like Apples and bananas \n"
    "I like fruits and yogurt\n"
    "thisUser: Your name : Mike Lewis\n"
    "Email: mike@mail.com\n"
    "type: Fullresopnse")

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)))

推荐阅读