微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

正则表达式:6位数或0-6个符号(数字或星号),至少有一颗星

如何编写正则表达式来验证这种模式?

123456 - correct
*1 - correct
1* - correct
124** - correct
*1*2 - correct
* - correct
123456* - incorrect (size 7)
12345 - incorrect (size 5 without stars)

尝试:

^[0-9]{6}$|^(([0-9]){1,6}([*]){1,5}){1,6}+$

但它允许有超过6个数字,并且不允许星号在数字之前.
没有“*”符号的最小/最大计数(但所有符号的最大计数为6).

解决方法

干得好:

^(?:\d{6}|(?=.*\*)[\d*]{1,6}|)$

这是它的作用:

^            <-- Start of the string (we don't want to capture more than that)
  (?:          <-- Start a non captured group (it will be used to do the "or" part)
    \d{6}          <-- 6 digits,nothing more
    |            <-- OR
    (?=.*\*)       <-- Look ahead for a '*' (you Could replace the first * with {0,5})
    [\d*]          <-- digits or '*'
    {1,6}          <-- repeated one to six times (we kNow from the look ahead that there will be at least one '*'
    |            <-- OR (nothing)
  )            <-- End the non capturing group
$           <-- End of the string

我不太确定你是否想要空的情况(但你说的是0到6),如果你真的想要1到6只是删除最后一个|

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐