我只想将子域的级别限制为 3 级。尝试下面的正则表达式失败
([\.]?[a-z]*){3}
我的目标:abc.def.ghi
但是
上面的正则表达式接受abc.def.ghi。
(注意最后一个。
)
最佳答案
使用
^(?:[a-z]+(?:\.[a-z]+){0,2})?$
参见proof .
说明
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
[a-z]+ any character of: 'a' to 'z' (1 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
(?: group, but do not capture (between 0 and
2 times (matching the most amount
possible)):
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
[a-z]+ any character of: 'a' to 'z' (1 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
){0,2} end of grouping
--------------------------------------------------------------------------------
)? end of grouping
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
关于javascript - 我想限制正则表达式中子域的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65332106/