javascript - 我想限制正则表达式中子域的数量

标签 javascript regex

我只想将子域的级别限制为 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/

相关文章:

javascript - 理解 typescript 生成的 __extends 函数?

javascript - Google Analytics 跟踪 FireFox 扩展的使用

mysql - PCRE Regex - 替换序列化字符串中的 URL

python - 正则表达式 : chopping last character if second last is upper case?

c# - 正则表达式 - 提取子串

javascript - 在 HTML javascript 中使用了 'needs-validattion' bootstrap,但它不会进入检查验证方法

javascript - 如何在 Laravel 中自定义 vue-filemanager 前端?

javascript - GraphQL 字段作为函数

java - 在哪里可以找到将正则表达式应用于输出的 Java Servlet 过滤器?

regex - 按相似词分组