python - 如何使用正则表达式在 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"
打印?
解决方案
这个表达式有一个返回 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)))
推荐阅读
- powershell - start-bitstransfer 是否与 pester 兼容
- php - Dotenv 和 void 类的 Symfony 4.1 错误
- node.js - 登录网站一次并使用请求重用会话
- java - 如何在 HQL 中使用内部联接进行更新
- javascript - 我怎样才能获得反应中的关键?
- javascript - 我的应用程序在奥利奥上崩溃。说应用程序再次停止打开应用程序
- java - org.springframework.web.servlet.PageNotFound noHandlerFound 在 spring mvc
- css - 浮动元素未清除到文档流中的新行
- java - 创建新的 MIDI 事件
- cordova - Ionic build android 因插件错误而失败