将“[”和“]”与regex一起使用时出现“列表索引超出范围”错误

2024-10-01 04:59:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在尝试获取一个包含方括号的输入来使用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。既然我已经指定了方括号在onetwothree中应该是分开的,为什么它仍然给出一个错误,我如何修复它?你知道吗

特定错误:

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”将正确输出。你知道吗


Tags: ofreinputoutputmatchrangeonesplit
1条回答
网友
1楼 · 发布于 2024-10-01 04:59:01

感谢肯尼奥斯特罗姆,答案揭晓!你知道吗

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。你知道吗

相关问题 更多 >