Home > Net >  python re unterminated character set at position 0
python re unterminated character set at position 0

Time:12-03

CODE:

import re
inp=input()
tup=tuple(map(str,inp.split(',')))
i=0
while i<len(tup):
    x=tup[i]
    a=re.search("[0-9a-zA-Z\$#@",x)
    if a!="None":
        break
    else:
        i=i 1
if a!="None" and len(tup[i])>=6 and len(tup[i])<=12:
    print(tup[i])
else:
    print("invalid")

INPUT: ABd1234@1,a F1#,2w3E*,2We3345

ERROR:

unterminated character set at position 0

CodePudding user response:

The error stems from the invalid regular expression - specifically, you've omitted the right-bracket.

However, even if you fix that, based on the code shown in the question, this isn't going to work for a couple of reasons.

  1. The return value from re.search will always be unequal to 'None'
  2. The final if test in the code is outside the while loop which is almost certainly not what's wanted.

Try this instead:

import string

VALIDCHARS = set(string.ascii_letters string.digits '$#@')

for word in input().split(','):
    if 6 <= len(word) <= 12 and all(c in VALIDCHARS for c in word):
        print(f'{word} is valid')
    else:
        print(f'{word} is invalid')

CodePudding user response:

Your regular expression is missing a closing bracket. It should be:

a=re.search("[0-9a-zA-Z\$#@]",x)

Also, replace all instances of "None" the string with None the keyword. This is because .search returns None as can be seen here.

https://docs.python.org/3/library/re.html#re.search

  • Related