Reputation: 86
I want to check whether the given string input is a number of six digits.
Valid:
* 123456
* 098765
Invalid:
* 123
* 12345a
* as3445
* /n123456
* 123456\n
My Python code:
bool(re.match("^[0-9]{6}$",string))
but this also matches "123456\n"
.
Why it is matching newline character and how to restrict this match?
Upvotes: 0
Views: 57
Reputation: 54148
As proposed in comment, \Z
: asserts position at the end of the string, or before the line terminator right at the end of the string
values = ["123456", "098765", "Invalid:", "123", "12345a", "as3445", "/n123456", "123456\n"]
for v in values:
print("{:10s} {}".format(v, bool(re.match("^[0-9]{6}\Z", v))))
123456 True
098765 True
Invalid: False
123 False
12345a False
as3445 False
/n123456 False
123456
False
Upvotes: 1