Python 如何匹配行中第一个字符后的字符串

Python 如何匹配行中第一个字符后的字符串,python,regex,Python,Regex,查找第一个匹配项的字符串 s = ''' Name Mak How are you Name non Name anonymouse Name Mak1 How are you Name non1 Name Mak2 How are you Name non2 ''' 如何提取名字 My Expected Out ['Mak', 'Mak1', 'Mak2'] 伪码 import re re.findall(r'?Name (([\w]+)',s) 这是一种使用str.split的方法 例

查找第一个匹配项的字符串

s = '''
Name Mak How are you Name non Name anonymouse
Name Mak1 How are you Name non1
Name Mak2 How are you Name non2
'''
如何提取名字

My Expected Out
['Mak', 'Mak1', 'Mak2']
伪码

import re
re.findall(r'?Name (([\w]+)',s)

这是一种使用str.split的方法

例:

输出:


这是一种使用str.split的方法

例:

输出:

您可以使用:

>>> s = '''
... Name Mak How are you Name non Name anonymouse
... Name Mak1 How are you Name non1
... Name Mak2 How are you Name non2
... '''
>>> re.findall(r'(?m)^Name (\w+)', s)
['Mak', 'Mak1', 'Mak2']
正则表达式详细信息:

?m启用多行模式 ^:开始 名称:匹配后跟空格的文本 \w+:匹配1+个单词字符并在组1中捕获 您可以使用:

>>> s = '''
... Name Mak How are you Name non Name anonymouse
... Name Mak1 How are you Name non1
... Name Mak2 How are you Name non2
... '''
>>> re.findall(r'(?m)^Name (\w+)', s)
['Mak', 'Mak1', 'Mak2']
正则表达式详细信息:

?m启用多行模式 ^:开始 名称:匹配后跟空格的文本 \w+:匹配1+个单词字符并在组1中捕获 细节

# Name - matches Name literally

# \s+ - matches one or more of white spaces

# ([^\s]+) - match one or more characters other from whitespace \s and store it inside first capturing group

# .+ - match one or more of any characters (except newline)
细节

# Name - matches Name literally

# \s+ - matches one or more of white spaces

# ([^\s]+) - match one or more characters other from whitespace \s and store it inside first capturing group

# .+ - match one or more of any characters (except newline)

在您提到的代码中,为了避免换行?当我们使用?m或多行模式时,我们可以在每一行的开头匹配^,这是为了避免换行?当我们使用?m或多行模式时,我们可以在每一行的开头匹配^1。再问一次,如果我们想提取第二个“名称”,有什么办法吗?如果您想要姓氏,请使用re.findallr.+Name\w+,s
# Name - matches Name literally

# \s+ - matches one or more of white spaces

# ([^\s]+) - match one or more characters other from whitespace \s and store it inside first capturing group

# .+ - match one or more of any characters (except newline)