0

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?

1
  • 3
    You could use ^[0-9]{6}\Z Commented Mar 21, 2020 at 8:36

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.