PYTHON
Validate a Simple Username with Regex
Use a Python regular expression to validate usernames, ensuring they are alphanumeric, can contain underscores, and meet specific length requirements.
import re
def is_valid_username(username):
# Username must be 3-16 characters long.
# Can contain alphanumeric characters (a-z, A-Z, 0-9) and underscores (_).
username_regex = re.compile(r'^[a-zA-Z0-9_]{3,16}$')
return bool(username_regex.match(username))
print(f"'john_doe123' is valid: {is_valid_username('john_doe123')}") # True
print(f"'user' is valid: {is_valid_username('user')}") # True
print(f"'me' is valid: {is_valid_username('me')}") # False (too short)
print(f"'a_very_long_username_that_is_too_long' is valid: {is_valid_username('a_very_long_username_that_is_too_long')}") # False (too long)
print(f"'user-name' is valid: {is_valid_username('user-name')}") # False (contains hyphen)
How it works: The `is_valid_username` function in Python checks if a username adheres to specific criteria using a regular expression `r'^[a-zA-Z0-9_]{3,16}$'`. This regex ensures that the username starts and ends (`^` and `$`) with only alphanumeric characters or underscores (`[a-zA-Z0-9_]`) and has a total length between 3 and 16 characters inclusive (`{3,16}`). `re.compile` is used for efficiency if the regex is applied multiple times, and `match()` checks if the pattern matches from the beginning of the string.