Search code examples
pythonpython-re

Mulitple occurance in a line - find first match only


I'm trying to learn regular expressions. How can I find the first occurrence of the email address given line below:

'   for somebody@domain.com  for   somebody@domain.com '

I was trying with occurrences as shown below:

et=re.findall('for (<.+@.+>){1}?','   for somebody@domain.com  for   somebody@domain.com ')

but without luck.


Solution

  • If you ignore strict email address validation which is mentioned here , you can use :

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

    click for demo