Python Programming Tips – Using re.match with Regular Expressions

In Python, the <span><span>re.match()</span></span> function is used to match a regular expression pattern at the beginning of a string. If the match is successful, it returns a match object; otherwise, it returns None. For example, it can be used to validate whether a username is valid (for instance, it must start with a letter). The code is as follows:

import re
# Validate username (must start with a letter)
def validate_username(username):
    pattern = r'^[a-zA-Z][a-zA-Z0-9_]{2,19}$'
    match = re.match(pattern, username)
    if match:
        return True, "Username format is correct"
    else:
        return False, "Username must start with a letter and be 3-20 characters long"

# Test cases
test_names = ["user123", "123user", "ab", "abc", "valid_user_2024"]
for name in test_names:
    is_valid, message = validate_username(name)
    print(f"'{name}': {message}")

Recommended Reading

  • 1-Line Code to Solve Narcissistic Number Determination

  • Basic Python Programming Algorithms – Narcissistic Number Determination

  • Combining lambda Functions with map

  • Python Programming Tips – lambda Functions and map
  • Writing Code on Mobile Devices
  • Python Programming Tips – Writing Code on Mobile Devices
  • Shuffling Algorithm

  • Basic Python Programming Algorithms – Shuffling Algorithm

  • LeetCode Jump Game (Greedy Algorithm)

  • Basic Python Programming Algorithms – LeetCode Jump Game (Greedy Algorithm)

<span><span>Today's Best-Selling Book - "</span></span><span><span><span>National Geographic Illustrated Encyclopedia of Everything</span></span></span><span><span><span>"</span></span></span>

  • Visually stunning presentation of the mysteries of everything, covering four major fields: flora and fauna, the human body, the universe, and the Earth. It integrates multidisciplinary knowledge, with content pieced together like a puzzle, suitable for both children and adults.A treasure book for shared reading

Leave a Comment