【问题标题】:Regex not to allow to consecutive dot characters and more正则表达式不允许连续的点字符等
【发布时间】:2019-05-27 05:18:47
【问题描述】:

我正在尝试制作一个满足以下条件的 JavaScript 正则表达式

  1. a-z 是可能的
  2. 0-9 是可能的
  3. 可以使用破折号、下划线、撇号、句号
  4. 和号、括号、逗号和加号是不可能的
  5. 连续的周期是不可能的
  6. 句号不能位于开头和结尾
  7. 最多 64 个字符

到目前为止,我已经开始关注正则表达式了

^[^.][a-zA-Z0-9-_\.']+[^.]$

但是,这允许中间有连续的点字符并且不检查长度。 谁能指导我如何添加这两个条件?

【问题讨论】:

  • 我希望使用 .length 属性的长度检查比某些 Regex 构造快得多。

标签: javascript regex


【解决方案1】:

你可以使用this正则表达式

^(?!^[.])(?!.*[.]$)(?!.*[.]{2})[\w.'-]{1,64}$

正则表达式分解

^ #Start of string
(?!^[.]) #Dot should not be in start
(?!.*[.]$) #Dot should not be in start
(?!.*[.]{2}) #No consecutive two dots
[\w.'-]{1,64} #Match with the character set at least one times and at most 64 times.
$ #End of string

正则表达式的更正

  • - 不应该介于字符类之间。它表示范围。避免在两者之间使用它
  • [a-zA-Z0-9_] 等价于 \w

【讨论】:

    【解决方案2】:

    这是一个似乎有效的模式:

    ^(?!.*\.\.)[a-zA-Z0-9_'-](?:[a-zA-Z0-9_'.-]{0,62}[a-zA-Z0-9_'-])?$
    

    Demo

    下面是正则表达式模式的解释:

    ^                          from the start of the string
        (?!.*\.\.)             assert that two consecutive dots do not appear anywhere
        [a-zA-Z0-9_'-]         match an initial character (not dot)
        (?:                    do not capture
        [a-zA-Z0-9_'.-]{0,62}  match to 62 characters, including dot
        [a-zA-Z0-9_'-]         ending with a character, excluding dot
         )?                    zero or one time
    $                          end of the string
    

    【讨论】:

      【解决方案3】:

      我的想法来了。使用\wshort 表示单词字符)。

      ^(?!.{65})[\w'-]+(?:\.[\w'-]+)*$
      
      • ^ start (?!.{65}) look ahead 不超过 64 个字符
      • 后跟[\w'-]+ 中的一个或多个[a-zA-Z0-9_'-]
      • 后跟(?:\.?[\w'-]+)* any amountnon capturing group 包含句点. 后跟一个或多个[a-zA-Z0-9_'-] 直到$ 结束

      还有demo at regex101 for trying

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-09
        • 1970-01-01
        • 2016-12-02
        • 2012-08-02
        • 2015-06-30
        • 2021-05-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多