0

Hi I would like to limit spaces in the following examples:

Text_1 = 'Your email: Peter @gmail.com Please enter your spouse's email: Mandy@gmail.com'
Extracted_1 = 'Peter @gmail.com'
Target_1 = 'Peter @gmail.com' (correct)

regex_pattern = r'Your email: [\s]?(.+@[\w.,-]+)'

Text_2 = 'Your email: Please enter your spouse's email: Mandy@gmail.com'
Extracted_2 = 'Please enter your spouse's email: Mandy@gmail.com'
Target_2 = '' (Empty)

With my current pattern, it will end up extracting everything up till the 2nd email. Is there a way where I can limit number of spaces?

Eg. limit 2 spaces so the 2nd example will return empty

Thanks!

Boon
  • 75
  • 4
  • 1
    Does this answer your question? [How can I validate an email address using a regular expression?](https://stackoverflow.com/questions/201323/how-can-i-validate-an-email-address-using-a-regular-expression) – Be Chiller Too Nov 16 '21 at 14:23

1 Answers1

0

You can exclude matching the @ to not cross it when matching.

Note that \s can also match a newline, and [\w.,-]+ is a character class also allowing for example only ,,,

\bYour email:[^\S\n]+([^@\n]+@[\w.,-]+)

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70