首页 > 解决方案 > 将“[”和“]”与正则表达式一起使用时出现“列表索引超出范围”错误

问题描述

我目前正在尝试获取包含方括号的输入以使用正则表达式。我的代码是:

#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")

问题是,对于包含任何方括号的输入,我得到一个 IndexError: 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

这仅适用于单个字母,例如“abc d”将正确输出。

标签: pythonregexpython-3.x

解决方案


感谢 Kenny Ostrom,答案揭晓!

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,所以我正在迭代超过输入的长度。


推荐阅读