Hi there, we’re Harisystems

"Unlock your potential and soar to new heights with our exclusive online courses! Ignite your passion, acquire valuable skills, and embrace limitless possibilities. Don't miss out on our limited-time sale - invest in yourself today and embark on a journey of personal and professional growth. Enroll now and shape your future with knowledge that lasts a lifetime!".

For corporate trainings, projects, and real world experience reach us. We believe that education should be accessible to all, regardless of geographical location or background.

1
1

Python Validations with Regular Expressions

Regular expressions (regex) provide a powerful and flexible way to validate and manipulate strings in Python. They allow you to define patterns and rules for matching and validating text data. In this article, we'll explore how to use regular expressions for data validations in Python, and provide examples to help you understand their implementation and usage.

Example 1: Email Validation

One common use case for regular expressions is email validation. Here's an example:

    import re

def validate_email(email):
    pattern = r'^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$'
    if re.match(pattern, email):
        return True
    return False

email = input("Enter an email address: ")
if validate_email(email):
    print("Valid email address.")
else:
    print("Invalid email address.")
  

In this code, we define a function called "validate_email" that takes an email address as input and uses a regular expression pattern to validate it. The pattern allows for a combination of alphanumeric characters, plus signs, periods, underscores, and hyphens before the @ symbol, followed by a domain name containing alphanumeric characters, periods, and hyphens. We use the "re.match" function to check if the entered email matches the pattern. If it does, we return True indicating a valid email address; otherwise, we return False.

Example 2: Phone Number Validation

Regular expressions can also be used for phone number validation. Here's an example:

    import re

def validate_phone_number(phone_number):
    pattern = r'^\d{3}-\d{3}-\d{4}$'
    if re.match(pattern, phone_number):
        return True
    return False

phone = input("Enter a phone number (format: XXX-XXX-XXXX): ")
if validate_phone_number(phone):
    print("Valid phone number.")
else:
    print("Invalid phone number.")
  

In this code, we define a function called "validate_phone_number" that takes a phone number as input and uses a regular expression pattern to validate it. The pattern specifies the format as three digits, followed by a hyphen, then three digits, another hyphen, and finally four digits. We use the "re.match" function to check if the entered phone number matches the pattern. If it does, we return True indicating a valid phone number; otherwise, we return False.

Example 3: Custom Validation Rules

You can create custom validation rules using regular expressions to meet specific requirements. Here's an example of validating a password:

    import re

def validate_password(password):
    pattern = r'^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)[A-Za-z\d]{8,}$'
    if re.match(pattern, password):
        return True
    return False

password = input("Enter a password: ")
if validate_password(password):
    print("Valid password.")
else:
    print("Invalid password.")
  

In this code, we define a function called "validate_password" that takes a password as input and uses a regular expression pattern to validate it. The pattern enforces the following rules:

  • At least one uppercase letter
  • At least one lowercase letter
  • At least one digit
  • Minimum length of 8 characters
We use the "re.match" function to check if the entered password matches the pattern. If it does, we return True indicating a valid password; otherwise, we return False.

Conclusion

Regular expressions provide a powerful tool for data validations in Python. By leveraging regex patterns, you can define custom rules for validating email addresses, phone numbers, passwords, and much more. Regular expressions are versatile and widely used in data processing and form validation tasks. Experiment with the examples provided and explore the possibilities of regular expressions in your Python projects.

4.5L

Learners

20+

Instructors

50+

Courses

6.0L

Course enrollments

4.5/5.0 5(Based on 4265 ratings)

Future Trending Courses

When selecting, a course, Here are a few areas that are expected to be in demand in the future:.

Beginner

The Python Course: Absolute Beginners for strong Fundamentals

By: Sekhar Metla
4.5 (13,245)
Intermediate

JavaScript Masterclass for Beginner to Expert: Bootcamp

By: Sekhar Metla
4.5 (9,300)
Intermediate

Python Coding Intermediate: OOPs, Classes, and Methods

By: Sekhar Metla
(11,145)
Intermediate

Microsoft: SQL Server Bootcamp 2023: Go from Zero to Hero

By: Sekhar Metla
4.5 (7,700)
Excel course

Future Learning for all

If you’re passionate and ready to dive in, we’d love to join 1:1 classes for you. We’re committed to support our learners and professionals their development and well-being.

View Courses

Most Popular Course topics

These are the most popular course topics among Software Courses for learners