RE newbie question

Ian Kelly ian.g.kelly at gmail.com
Wed Apr 18 16:06:57 EDT 2018


On Wed, Apr 18, 2018 at 1:57 PM, Rob Gaddi
<rgaddi at highlandtechnology.invalid> wrote:
> On 04/18/2018 12:37 PM, TUA wrote:
>>
>> import re
>>
>> compval = 'A123456_8'
>> regex = '[a-zA-Z]\w{0,7}'
>>
>> if re.match(regex, compval):
>>     print('Yes')
>> else:
>>     print('No')
>>
>>
>> My intention is to implement a max. length of 8 for an input string. The
>> above works well in all other respects, but does allow for strings that are
>> too long.
>>
>> What is the proper way to fix this?
>>
>> Thanks for any help!
>>
>
> You could put the end marker $ on your regex so that it won't match if it's
> not the end.
>
> Or, you know, you could just check len(compval) <= 8 and not get bogged down
> in regexes.  They tend to be excellent solutions to only a very specific
> complexity of problem.

In Python 3.4+ you can also use re.fullmatch which requires a match
against the entire string.


More information about the Python-list mailing list