How do I verify that a string only contains letters, numbers, underscores and dashes? [duplicate]

A regular expression will do the trick with very little code:

import re

...

if re.match("^[A-Za-z0-9_-]*$", my_little_string):
    # do something here

Leave a Comment