我目前正在尝试获取一个包含方括号的输入来使用regex。我的代码是:
#groups of characters
one = r"[a-zA-Z0-9\!\@\$\%\^\*\(]"
two = "[" + r"[a-zA-Z0-9\!\@\$\%\^\*\(][a-zA-Z0-9\!\@\$\%\^\*\(]" + "]"
three = "[" + r"[a-zA-Z0-9\!\@\$\%\^\*\(][a-zA-Z0-9\!\@\$\%\^\*\(][a-zA-Z0-9\!\@\$\%\^\*\(]" + "]"
rawInput = input("Please send text:\n") #raw input
wInput = rawInput.replace(" ","") #whitespace free input
uInput = re.split(r"\s",rawInput) #split input
output = [] #start of output
for i in range(1,(len(wInput))):
if re.match(one,uInput[i]): #1 char
output.append("Send {" + str(uInput[i])+"}\n")
elif re.match(two,uInput[i]): #2 chars
uInput[i].split()
output.append("Send {" + uInput[i][1] + "} {" + uInput[i][2] + "}\n")
elif re.match(three,uInput[i]): #3 chars
uInput[i].split()
output.append("Send {" + uInput[i][1] + "} {" + uInput[i][2] + "} {" + uInput[i][3] + "}\n")
问题是,对于包含任何方括号的输入,会给我一个indexeror:list index out-of-range。既然我已经指定了方括号在one
、two
和three
中应该是分开的,为什么它仍然给出一个错误,我如何修复它?你知道吗
特定错误:
Traceback (most recent call last):
File "main.py", line 18, in <module>
if re.match(one,uInput[i]): #1 char
IndexError: list index out of range
这只适用于单个字母,例如“a b c d”将正确输出。你知道吗
感谢肯尼奥斯特罗姆,答案揭晓!你知道吗
input '[one]' has len 5, uInput has length 1, uInput[i] fails with i=1, has nothing to do with re, the exception tells why – Kenny Ostrom 2 hours ago
我在迭代输入的长度,因为我使用了wInput而不是uInput。你知道吗
相关问题 更多 >
编程相关推荐