Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regular expression for matching 3 and 16 characters

Tags:

python

regex

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)
like image 482
GrantU Avatar asked Apr 16 '26 03:04

GrantU


2 Answers

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.

like image 144
poke Avatar answered Apr 17 '26 15:04

poke


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.

like image 39
Elazar Avatar answered Apr 17 '26 16:04

Elazar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!