正则表达式: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只是删除最后一个|

相关文章

正则替换html代码中img标签的src值在开发富文本信息在移动端...
正则表达式
AWK是一种处理文本文件的语言,是一个强大的文件分析工具。它...
正则表达式是特殊的字符序列,利用事先定义好的特定字符以及...
Python界一名小学生,热心分享编程学习。
收集整理每周优质开发者内容,包括、、等方面。每周五定期发...