Understand why regex-based email and phone checks have limits.
How It Works
Regular expressions can check an intentionally simple local format, but real email syntax and international telephone numbering are more complex. Validate input length, use a maintained parser when appropriate, and verify ownership through a separate workflow.
Step-by-Step Example
import re
email_shape = re.compile(r'[^\s@]+@[^\s@]+\.[^\s@]+')
print(bool(email_shape.fullmatch('[email protected]')))
print(bool(email_shape.fullmatch('not an email')))
Understanding the Example
- The expression "re.compile(r'[^\\s@]+@[^\\s@]+\\.[^\\s@]+')" supplies the value stored as 'email_shape'. This value is then used or checked by the later statements.
- The print() call exposes the result so you can compare it with the behavior described above. Check the value and its type when experimenting.
A successful run of this example prints the following output:
True
False
Where This Fits in a Real Program
Start by writing down examples that should match and examples that must fail. Check whether you need to locate a substring, match a prefix or validate an entire field; these are different operations. Unicode and escape sequences can also change which characters are matched, so test accented text and empty input.
Practice: Try It Yourself
Regex should enforce only the constraints your application can describe reliably.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Treating a simplified regex as proof that an address exists, or rejecting legitimate international formats unnecessarily.
- Create a basic UI format check and follow it with an email verification step.
Key Takeaways
- Understand why regex-based email and phone checks have limits.
- Regular expressions can check an intentionally simple local format, but real email syntax and international telephone numbering are more complex.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.