正则表达式 – 正则表达式匹配字符串
发布时间:2020-12-14 05:49:46 所属栏目:百科 来源:网络整理
导读:我希望按照以下规则匹配所有令人满意的字符串 – 应包含小写字母,数字和短划线 应该以字母或数字开头 应以字母或数字结尾 总字符串长度应至少为3个字符,最多为20个字符 点.是可选的,不应该有两个或多个连续的点. 破折号 – 是可选的,不应该有两个或更多连续
我希望按照以下规则匹配所有令人满意的字符串 –
>应包含小写字母,数字和短划线 我想出了这个正则表达式: ^[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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |