gpt4 book ai didi

regex - 匹配字符串的正则表达式

转载 作者:行者123 更新时间:2023-12-01 01:16:33 25 4
gpt4 key购买 nike

我想匹配满足以下规则的所有字符串-

  • 应该由小写字母、数字和破折号组成
  • 应该以字母或数字开头
  • 应该以字母或数字结尾
  • 总字符串长度应至少为 3 到 20 个字符
  • .是可选的,不应有两个或多个连续的点 .
  • 破折号 -是可选的,不应有两个或多个连续的破折号 -
  • .和破折号 -不应该是连续的//字符串 aaa.-aaabbb无效
  • 不允许下划线

  • 我想出了这个正则表达式:
    ^[a-z0-9]([a-z0-9]+\.?\-?[a-z0-9]+){1,18}[a-z0-9]$

    [a-z0-9] //should start/end with a letter or a number
    ([a-z0-9]+\.?\-?[a-z0-9]+){1,18} //other rules

    但是在某些情况下它会失败,例如 -
    abcdefghijklmnopqrstuvwxyz //should fail total number of chars greater than 20  
    aaa.-aaabbb //should fail as dot '.' and dash '-' are consecutive

    任何人都可以帮我纠正这个正则表达式吗?

    最佳答案

    您可以使用 lookahead assertion 来实现这一点。 :

    ^(?!.*[.-]{2})[a-z0-9][a-z0-9.-]{1,18}[a-z0-9]$

    说明:
    ^                # Start of string
    (?! # Assert that the following can't be matched:
    .* # Any number of characters
    [.-]{2} # followed by .. or -- or .- or -.
    ) # End of lookahead
    [a-z0-9] # Match lowercase letter/digit
    [a-z0-9.-]{1,18} # Match 1-18 of the allowed characters
    [a-z0-9] # Match lowercase letter/digit
    $ # End of string

    关于regex - 匹配字符串的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11776961/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com