我希望按照以下规则匹配所有令人满意的字符串 –
>应包含小写字母,数字和短划线
>应该以字母或数字开头
>应以字母或数字结尾
>总字符串长度应至少为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