Why is the allowRegexes keyword in pyinputplus allowing ABC in pyip.inputNum(allowRegexes=[r'(C)+'])?

Viewed 289

Working through Automate the Boring Stuff, and can't see why allowRegexes keyword in pyinputplus doesn't seem to be working for me.

for example

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

It seems as though as long as I input any string containing C it will be allowed. But it should be only C or CCCC... that should pass I think.

I can't see that anyone else had issues with this. Is this some issue with Python versions, or am I missing something and being a regular expression donut?

1 Answers

The issue is either within your assumption of how the parameter allowRegexes works, or in your regex. Though I guess it's probably the former.

The behavior is this: If the regex set in allowRegexes matches any part of the input, the whole string will be valid (respectively invalid, if used in blockRegexes). The regex does not need to match the entire input. Granted, that may not be completely clear from the wording in the documentation, but the examples listed in the description of pyinputplus.inputInt() illustrate this behavior.

Since (C)+ will match any C in a string, any sequence that contains a C anywhere will pass validation, as you observed. If you wanted only sequences of C without spaces, like C, CC, CCC, etc., to be added as valid input, your regex could e.g. look like this: ^C+$. See 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'
Related