Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我想限制正则表达式中子域的数目_Javascript_Regex - Fatal编程技术网

Javascript 我想限制正则表达式中子域的数目

Javascript 我想限制正则表达式中子域的数目,javascript,regex,Javascript,Regex,我想限制子域的级别仅为3级。尝试下面的正则表达式失败 ([\.]?[a-z]*){3} 我的目标:abc.def.ghi 但是 上面的正则表达式接受abc.def.ghi。(注意最后一个)使用 ^(?[a-z]+(?:\[a-z]+){0,2})$ 看 解释 -------------------------------------------------------------------------------- ^ the beginn

我想限制子域的级别仅为3级。尝试下面的正则表达式失败

([\.]?[a-z]*){3}
我的目标:
abc.def.ghi

但是

上面的正则表达式接受abc.def.ghi。(注意最后一个

使用

^(?[a-z]+(?:\[a-z]+){0,2})$

解释

--------------------------------------------------------------------------------
  ^                        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

因为regexp没有锚定,所以它匹配字符串中的任何位置。非常感谢!9分钟后接受正确答案。