Regex scenarios to Capture Specific Email Domains in Python's re Module
I'm experimenting with I'm relatively new to this, so bear with me. I tried several approaches but none seem to work. I'm trying to validate a list of email addresses in Python, specifically looking to ensure they come from certain domains (e.g., `example.com`, `test.org`). I thought using regex would be a straightforward way to do this, but I'm running into issues where some valid emails are incorrectly flagged as invalid. Here's the regex pattern I'm currently using: ```python import re email_pattern = r'^[a-zA-Z0-9._%+-]+@(example\.com|test\.org)$' valid_emails = ['user@example.com', 'admin@test.org', 'info@wrongdomain.com'] for email in valid_emails: if re.match(email_pattern, email): print(f'{email} is valid') else: print(f'{email} is invalid') ``` When I run this, I get the expected output for `user@example.com` and `admin@test.org`, but I also want to ensure that emails like `user.name@example.com` are caught as valid, but they’re not. The regex seems too restrictive when it comes to the username part, which can actually include dots and other characters. I've tried modifying my regex like this: ```python email_pattern = r'^[a-zA-Z0-9._%+-]+@(example\.com|test\.org)$' ``` But this doesn’t seem to help either. Furthermore, I'm unsure if I'm handling edge cases properly—for example, what about emails with subdomains like `user@mail.example.com`? I’d like to restrict matches strictly to the domains specified, and I’m worried about performance as well with a larger list of emails. Could anyone suggest an improved regex pattern or a better approach to validate these email addresses? I’m using Python 3.9.x and the `re` module for regex operations. This is part of a larger API I'm building. I'm working in a Linux environment. For reference, this is a production application. What's the correct way to implement this?