python - 为什么 pyinputplus 中的allowRegexes关键字允许在pyip.inputNum(allowRegexes=[r'(C)+'])中使用ABC?

标签 python python-3.x regex

通过自动化无聊的东西,不明白为什么 pyinputplus 中的 allowRegexes 关键字似乎对我不起作用。

例如

>>> import pyinputplus as pyip
>>> pyip.inputNum('input: ', allowRegexes=[r'(C)+'])
input: AB
'AB' is not a number.
input: ABC
'ABC'

似乎只要我输入任何包含C的字符串就会被允许。但我认为应该只有 CCCCC... 应该通过。

我看不出其他人对此有任何问题。这是Python版本的问题吗,还是我遗漏了一些东西并且成为了正则表达式 donut ?

最佳答案

问题要么出在您对参数 allowRegexes 如何工作的假设中,要么出在您的正则表达式中。虽然我猜可能是前者。

行为是这样的:如果allowRegexes中设置的正则表达式与输入的任何部分匹配,则整个字符串将有效(如果在中使用,则分别无效>阻止正则表达式)。正则表达式不需要匹配整个输入。当然,从 documentation 中的措辞来看,这一点可能并不完全清楚。 ,但是 description of pyinputplus.inputInt() 中列出的示例说明这种行为。

由于 (C)+ 将匹配字符串中的任何 C,因此任何位置包含 C 的任何序列都将通过验证,因为您观察到的。如果您只想使用不带空格的 C 序列,例如 CCCCCC 等,添加为有效输入,您的正则表达式可以例如看起来像这样:^C+$。请参阅https://regex101.com/r/x03Fes/1

>>> import pyinputplus as pyip
>>> pyip.inputNum('input: ', allowRegexes=[r'^C+$'])
input: ABC
'ABC' is not a number.
input: ACB
'ACB' is not a number.
input: CAB
'CAB' is not a number.
input: CAC
'CAC' is not a number.
input: CCC CCC
'CCC CCC' is not a number.
input: CCC
'CCC'

关于python - 为什么 pyinputplus 中的allowRegexes关键字允许在pyip.inputNum(allowRegexes=[r'(C)+'])中使用ABC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65878147/

相关文章:

Python for 循环和 "sum13"方法

python - 运行代码与在 VSCODE 终端中运行 Python 文件

python-3.x - 我想使用命令提示符安装 cv2

php - 使用 preg_replace 替换空段落,无法识别空格

python - 在 Python 中用 NaN 替换数值

python flask 模板返回前 150 个字符

python - 在 python 中只能检索一次压缩值吗?

python - 时间格式正则表达式 HH :MM AM/am/PM/pm in python

javascript - 将字符串拆分为单词并保留定界符

Python重启程序