Validating Strings as Alphanumeric Using Regex in Python

To validate alphanumeric characters using regular expressions, use ^[a-zA-Z0-9]+$. This regular expression matches strings composed of one or more alphanumeric characters, such as "3DModel".

If you want to specify a fixed length of alphanumeric characters, use ^[a-zA-Z0-9]{n}$. For example, to match exactly 6 characters, use ^[a-zA-Z0-9]{6}$. Similarly, you can create flexible patterns by specifying minimum and maximum lengths. For instance, ^[a-zA-Z0-9]{12,20}$ is effective for matching strings between 12 and 20 characters.

Below is a summary of commonly used regular expression patterns. Feel free to use them as needed.

#Match ConditionRegular Expression Pattern
1Contains only alphanumeric characters^[a-zA-Z0-9]+$
2Fixed length of n alphanumeric characters^[a-zA-Z0-9]{n}$
3At least n alphanumeric characters^[a-zA-Z0-9]{n,}$
4No more than m alphanumeric characters^[a-zA-Z0-9]{1,m}$
5Between n and m alphanumeric characters^[a-zA-Z0-9]{n,m}$
A list of common regular expression patterns for validating alphanumeric

Source Code

Below is a Python function to validate if a given string consists only of alphanumeric characters. The function allows validation based on the following conditions:

  • If the minimum length is omitted: Validates that the string is within the specified maximum length and consists only of alphanumeric characters.
  • If the maximum length is omitted: Validates that the string meets the minimum length requirement and consists only of alphanumeric characters.
  • If both minimum and maximum lengths are omitted: Validates that the string entirely consists of alphanumeric characters.
import re

def validate_args_type(string, min_length, max_length):
    """Validates the types of the arguments"""
    if not isinstance(string, str):
        raise TypeError("The input string must be of type 'str'.")

    if min_length is not None and not isinstance(min_length, int):
        raise TypeError("The minimum length (min_length) must be of type 'int'.")

    if max_length is not None and not isinstance(max_length, int):
        raise TypeError("The maximum length (max_length) must be of type 'int'.")

def is_alphanumeric(string, min_length=None, max_length=None):
    """
    Checks whether a string consists only of alphanumeric characters.

    Args:
        string (str): The input string to validate.
        min_length (int or None): The minimum length (defaults to 1 if None is provided).
        max_length (int or None): The maximum length (defaults to the length of the string if None is provided).

    Returns:
        bool: Returns True if the string meets the conditions, otherwise returns False.
    """
    # Validate the argument types
    validate_args_type(string, min_length, max_length)

    # Set default values
    min_len = min_length or 1
    max_len = max_length or len(string)

    # Validate the range of minimum and maximum lengths
    if min_len < 1:
        raise ValueError("The minimum length (min_length) must be an integer greater than or equal to 1.")

    if max_length is not None and max_len < min_len:
        raise ValueError("The maximum length (max_length) must be greater than or equal to the minimum length (min_length).")

    # Build the regex pattern
    if max_length is None:
        pattern = re.compile(f"^[a-zA-Z0-9]{{{min_len},}}$")
    else:
        pattern = re.compile(f"^[a-zA-Z0-9]{{{min_len},{max_len}}}$")

    # Validate using the regex pattern
    return bool(pattern.match(string))

Test Cases

# True: Meets the condition
print(is_alphanumeric("hello123", min_length=3, max_length=10))

# False: Does not meet the minimum length
print(is_alphanumeric("hello123", min_length=10))

# False: Contains non-alphanumeric characters
print(is_alphanumeric("hello!123", min_length=1))

# False: Exceeds the maximum length
print(is_alphanumeric("abc", max_length=2))

# True: Contains only alphanumeric characters and meets the condition
print(is_alphanumeric("ABC123", min_length=1, max_length=6))

# False: An empty string does not meet the condition
print(is_alphanumeric("", min_length=1))

Follow me!

photo by:Rubaitul Azad