python - 将“[”和“]”与正则表达式一起使用时出现“列表索引超出范围”错误
问题描述
我目前正在尝试获取包含方括号的输入以使用正则表达式。我的代码是:
#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”将正确输出。
解决方案
感谢 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,所以我正在迭代超过输入的长度。
推荐阅读
- java - org.openqa.selenium.NoSuchElementException:在检查条件时,使用给定的搜索参数无法在页面上找到一个元素
- oauth-2.0 - 为什么我的客户端没有打开 oauth2 url?
- reactjs - FastField 在 Formik 中没有按预期工作
- heroku - Heroku WSS 突然无法验证
- telerik-reporting - 在 Telerik 报告中,如何从 appsettings.json 设置 Web 服务数据源 url?
- angular - Angular 7 Google Recaptcha v 2 构建时出错
- reactjs - 在调用 React JS 的 Component 处获取子组件中 react redux 的值
- html - 当元素被拖离容器很远时,从 Angular Materials cdkDropList 中删除拖动项
- r - 映射嵌套列并计算两组之间的 t 检验
- java - Arraytypes 内嵌套对象的 JSON 解析