[英]Regex matching newline character by default in python
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:我的 Python 代码:
bool(re.match("^[0-9]{6}$",string))
but this also matches "123456\\n"
.但这也匹配
"123456\\n"
。
Why it is matching newline character and how to restrict this match?为什么它匹配换行符以及如何限制这种匹配?
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正如评论中所建议的,
\\Z
:在字符串的末尾断言位置,或在字符串末尾的行终止符之前
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.