I know how to do this if I iterate through all of the characters in the string but I am looking for a more elegant method.
Regular expression can be very flexible.
import re;
re.fullmatch("^[\w-]+$", target_string) # fullmatch looks also workable for python 3.4
\w
: Only [a-zA-Z0-9_]
So you need to add -
char for justify hyphen char.
+
: Match one or more repetitions of the preceding char. I guess you don't accept blank input. But if you do, change to *
.
^
: Matches the start of the string.
$
: Matches the end of the string.
You need these two special characters since you need to avoid the following case. The unwanted chars like &
here might appear between the matched pattern.
&&&PATTERN&&PATTERN