Hackerss.com

hackerss
hackerss

Posted on

Python Validate that input text only accept letters and numbers with regex


import re

def validate(text):
    """
    Validate that input text only accept letters and numbers with regex.

    Parameters
    ----------
    text : str
        Text to validate.

    Returns
    -------
    bool
        ``True`` if ``text`` is valid, ``False`` otherwise.
    """

    #return True if the text only contains letters and numbers, False otherwise
    return bool(re.match('^[a-zA-Z0-9]+$', text))

#example
validate('abc123')  #True
validate('abc 123')  #False
validate('abc')  #True
validate('abc!')  #False
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)