正则表达式允许字符串只包含数字 0 - 9 并将长度限制为 45 [英] Regex allow a string to only contain numbers 0 - 9 and limit length to 45
问题描述
我正在尝试创建一个正则表达式,让字符串只包含 0-9
作为字符,并且长度必须至少为 1 个字符且不超过 45
.因此,例如 00303039
将是匹配项,而 039330a29
则不会.
I am trying to create a regex to have a string only contain 0-9
as the characters and it must be at least 1 char in length and no more than 45
. so example would be 00303039
would be a match, and 039330a29
would not.
到目前为止,这是我所拥有的,但我不确定它是否正确
So far this is what I have but I am not sure that it is correct
[0-9]{1,45}
我也试过
^[0-9]{45}*$
但这似乎也不起作用.我对正则表达式不是很熟悉,所以任何帮助都会很棒.谢谢!
but that does not seem to work either. I am not very familiar with regex so any help would be great. Thanks!
推荐答案
大功告成,您只需要开始锚点 (^
) 和结束锚点 ($
):
You are almost there, all you need is start anchor (^
) and end anchor ($
):
^[0-9]{1,45}$
\d
是字符类 [0-9]
的缩写.您可以将其用作:
\d
is short for the character class [0-9]
. You can use that as:
^\d{1,45}$
锚点强制模式匹配整个输入,而不仅仅是它的部分.
The anchors force the pattern to match entire input, not just a part of it.
您的正则表达式 [0-9]{1,45}
查找 1 到 45 位数字,因此像 foo1
这样的字符串也会匹配,因为它包含 1代码>.
Your regex [0-9]{1,45}
looks for 1 to 45 digits, so string like foo1
also get matched as it contains 1
.
^[0-9]{1,45}
查找 1 到 45 位数字,但这些数字必须位于开头输入.它匹配 123
但也匹配 123foo
^[0-9]{1,45}
looks for 1 to 45 digits but these digits must be at the beginning of the input. It matches 123
but also 123foo
[0-9]{1,45}$
查找 1 到 45 位数字,但这些数字必须位于结尾输入.它匹配 123
但也匹配 foo123
[0-9]{1,45}$
looks for 1 to 45 digits but these digits must be at the end of the input. It matches 123
but also foo123
^[0-9]{1,45}$
查找 1 到 45 个数字,但这些数字必须两者在开始和结束输入,实际上它应该是整个输入.
^[0-9]{1,45}$
looks for 1 to 45 digits but these digits must be both at the start and at the end of the input, effectively it should be entire input.
这篇关于正则表达式允许字符串只包含数字 0 - 9 并将长度限制为 45的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!