一行中多次出现 - 仅查找第一个匹配项
Mulitple occurance in a line - find first match only
我正在努力学习正则表达式。我怎样才能找到下面给定行的电子邮件地址的第一次出现:
' for somebody@domain.com for somebody@domain.com '
我正在尝试如下所示的事件:
et=re.findall('for (<.+@.+>){1}?',' for somebody@domain.com for somebody@domain.com ')
但运气不好。
如果您忽略here提到的严格电子邮件地址验证,您可以使用:
import re
pattern = r'\S+@\S+'
string = ' for somebody@domain.com for somebody@domain.com '
try:
first_match = next(re.finditer(pattern, string))
print(first_match.group())
except StopIteration:
print('No match found')
点击 demo
我正在努力学习正则表达式。我怎样才能找到下面给定行的电子邮件地址的第一次出现:
' for somebody@domain.com for somebody@domain.com '
我正在尝试如下所示的事件:
et=re.findall('for (<.+@.+>){1}?',' for somebody@domain.com for somebody@domain.com ')
但运气不好。
如果您忽略here提到的严格电子邮件地址验证,您可以使用:
import re
pattern = r'\S+@\S+'
string = ' for somebody@domain.com for somebody@domain.com '
try:
first_match = next(re.finditer(pattern, string))
print(first_match.group())
except StopIteration:
print('No match found')
点击 demo