加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 06:06:29 所属栏目:百科 来源:网络整理
导读:如何编写正则表达式来验证这种模式? 123456 - correct*1 - correct1* - correct124** - correct*1*2 - correct* - correct123456* - incorrect (size 7)12345 - incorrect (size 5 without stars) 尝试: ^[0-9]{6}$|^(([0-9]){1,6}([*]){1,5}){1,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只是删除最后一个|

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读