Reputation: 6555
I'm new to regular expressions and I'm trying to produce in Python the following condition.
String between 3 and 16 characters long and being alpha-numeric or containing a hyphen (but not as the first or last character).
This is what I have so far:
rule = re.compile(r'(^{0,16})')
if rule.search(value):
msg = u"Does not validate"
raise ValidationError(msg)
Upvotes: 2
Views: 463
Reputation: 21635
You can use format
to shorten it:
'{0}({0}|-){1}{0}'.format('[a-zA-Z0-9]','{1-14}')
@poke's version is better if the requirement for case-insensitivity is inherent to the whole query.
Upvotes: 3
Reputation: 388053
re.compile('[A-Z0-9][A-Z0-9-]{1,14}[A-Z0-9]', re.I)
This will accept alpha-numeric character at the beginning and at the end, and require 1 too 14 alpha-numeric or hypen characters in between.
Upvotes: 6