我正在寻找一种方法来提取一行中的最后一个单词。我只想提取名字: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)))
关于python - 如何使用正则表达式在Python中获取段落中的最后一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56801278/