GrantU
GrantU

Reputation: 6555

Python regular expression for matching 3 and 16 characters

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

Answers (2)

Elazar
Elazar

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

poke
poke

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

Related Questions