通过自动化无聊的东西,不明白为什么 pyinputplus
中的 allowRegexes
关键字似乎对我不起作用。
例如
>>> import pyinputplus as pyip
>>> pyip.inputNum('input: ', allowRegexes=[r'(C)+'])
input: AB
'AB' is not a number.
input: ABC
'ABC'
似乎只要我输入任何包含C
的字符串就会被允许。但我认为应该只有 C
或 CCCC...
应该通过。
我看不出其他人对此有任何问题。这是Python版本的问题吗,还是我遗漏了一些东西并且成为了正则表达式 donut ?
最佳答案
问题要么出在您对参数 allowRegexes
如何工作的假设中,要么出在您的正则表达式中。虽然我猜可能是前者。
行为是这样的:如果allowRegexes
中设置的正则表达式与输入的任何部分匹配,则整个字符串将有效(如果在中使用,则分别无效>阻止正则表达式
)。正则表达式不需要匹配整个输入。当然,从 documentation 中的措辞来看,这一点可能并不完全清楚。 ,但是 description of pyinputplus.inputInt()
中列出的示例说明这种行为。
由于 (C)+
将匹配字符串中的任何 C
,因此任何位置包含 C
的任何序列都将通过验证,因为您观察到的。如果您只想使用不带空格的 C
序列,例如 C
、CC
、CCC
等,添加为有效输入,您的正则表达式可以例如看起来像这样:^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/