6位正则表达式 [英] 6 digits regular expression
问题描述
我需要一个至少需要一位数字和最多六位数字的正则表达式.
I need a regular expression that requires at least ONE digits and SIX maximum.
我已经解决了这个问题,但它们似乎都不起作用.
I've worked out this, but neither of them seems to work.
^[0-9][0-9]\?[0-9]\?[0-9]\?[0-9]\?[0-9]\?$
^[0-999999]$
还有什么建议吗?
推荐答案
您可以使用范围量词 {min,max}
指定最小 1 位和最大 6 位为:
You can use range quantifier {min,max}
to specify minimum of 1 digit and maximum of 6 digits as:
^[0-9]{1,6}$
说明:
^ : Start anchor
[0-9] : Character class to match one of the 10 digits
{1,6} : Range quantifier. Minimum 1 repetition and maximum 6.
$ : End anchor
为什么你的正则表达式不起作用?
您几乎接近正则表达式:
You were almost close on the regex:
^[0-9][0-9]\?[0-9]\?[0-9]\?[0-9]\?[0-9]\?$
由于您通过在 \
前面对 ?
进行转义,?
不再充当正则表达式元字符 (0
或 1
重复),但按字面处理.
Since you had escaped the ?
by preceding it with the \
, the ?
was no more acting as a regex meta-character ( for 0
or 1
repetitions) but was being treated literally.
要修复它,只需删除 \
即可.
To fix it just remove the \
and you are there.
基于量词的正则表达式更短、更易读并且可以轻松扩展到任意数量的数字.
The quantifier based regex is shorter, more readable and can easily be extended to any number of digits.
你的第二个正则表达式:
Your second regex:
^[0-999999]$
相当于:
^[0-9]$
只匹配一位数字的字符串.它们是等价的,因为字符类 [aaaab]
与 [ab]
相同.
which matches strings with exactly one digit. They are equivalent because a character class [aaaab]
is same as [ab]
.
这篇关于6位正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!