如何编写正则表达式来验证这种模式?
123456 - correct
*1 - correct
1* - correct
124** - correct
*1*2 - correct
* - correct
123456* - incorrect (size 7)
12345 - incorrect (size 5 without stars)
Run Code Online (Sandbox Code Playgroud)
尝试:
^[0-9]{6}$|^(([0-9]){1,6}([*]){1,5}){1,6}+$
Run Code Online (Sandbox Code Playgroud)
但它允许有超过6个数字,并且不允许星号在数字之前.没有"*"符号的最小/最大计数(但所有符号的最大计数为6).
Col*_*ert 14
干得好:
^(?:\d{6}|(?=.*\*)[\d*]{1,6}|)$
Run Code Online (Sandbox Code Playgroud)
这是它的作用:
^ <-- 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
Run Code Online (Sandbox Code Playgroud)
我不太确定你是否想要空壳(但你说的是0到6),如果你真的想要1到6只是删除最后一个 |