python - 如何使用正则表达式在Python中获取段落中的最后一个单词

标签 python regex

我正在寻找一种方法来提取一行中的最后一个单词。我只想提取名字: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”

最佳答案

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

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

Demo

测试

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

关于python - 如何使用正则表达式在Python中获取段落中的最后一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56801278/

相关文章:

python - 内置 all() 函数不在负数列表上返回 True

python - 如何在 Python 中添加一个字符串和一个 int 对象?

javascript - 用正则表达式拆分和替换 javascript 中的 unicode 单词

Javascript提取字符串中的未知数字

python - 日期时间转换 - 如何提取推断的格式?

python - 如何根据子列表的长度对列表列表进行排序

python - 我有一个形状为 (601, 2522) 的数据框。我希望索引从数据帧的第二行开始

c# - 滑动正则表达式语法 C#

javascript - 提取元素内的所有有效 URL 字符串 (JavaScript)

regex - 如何通过正则表达式识别 "text"单词?