RegEx in Pythion

RegEx is Amazing. It is a powerful tool in Python that is used to find matching patterns in text. Python provides the built in ‘re’ ‘module to work with regular expressions.

Below are some key functions in the re module:

  • re.match(): Checks for a match only at the beginning of the string.
  • re.search(): Searches the string for a match, and returns a match object if found.
  • re.findall(): Returns a list of all matches in the string.
  • re.finditer(): Returns an iterator yielding match objects for all matches in the string.
  • re.sub(): Replaces one or many matches with a string.

Email Validation Regex

Let’s write a regex to validate email addresses that are between 8 and 50 characters long.

Regex Pattern

Explanation

  1. ^(?=.{8,50}$):
    • ^: Asserts the position at the start of the string.
    • (?=.{8,50}$): Positive lookahead to ensure the string length is between 8 and 50 characters.
      • .{8,50}: Matches any character (except newline) between 8 and 50 times.
      • $: Asserts the position at the end of the string.
  2. [A-Za-z0-9._%+-]+:
    • Matches the local part of the email address.
    • [A-Za-z0-9._%+-]: Matches any alphanumeric character or . % + - _.
    • +: Ensures one or more occurrences.
  3. @:
    • Matches the @ symbol.
  4. [A-Za-z0-9.-]+:
    • Matches the domain part of the email address.
    • [A-Za-z0-9.-]: Matches any alphanumeric character, . or -.
    • +: Ensures one or more occurrences.
  5. \.[A-Za-z]{2,}:
    • \.: Matches a literal dot.
    • [A-Za-z]{2,}: Matches the top-level domain (TLD) which is at least two alphabetic characters.
  6. $:
    • Asserts the position at the end of the string.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top