我需要一个正则表达式,它匹配以字母开头和结尾的字符串,其中包含4-8个字符:A-z、-、_和.。
字符串不能包含两个或多个连续的-、.或_字符。
没有连续限制的Regex是^[A-z][A-z_\\.\\-]{4,8}[A-z]$,如何在这里添加一个限制,或者可能是不可能的?
我知道,在regex中对特定单词进行否定的一种更好的方法是负展望,但我不知道如何在这里实现它。
发布于 2013-09-19 18:20:08
您可以预先使用负面的前瞻性来检查该字符类中没有任何连续字符。尝试使用这个regex:
str.matches("(?!.*([._-])\\1)[A-Za-z][a-zA-Z._-]{4,8}[a-zA-Z]");解释:
(?! // Start negative look-ahead (not followed by)
.* // Any string
( // Start capture group 1
[._-] // Any of ., _, -
)
\\1 // \1 (escaped \\1) Same character captured in capture group 1 (avoid consecutive)
) // Look-ahead ends
[A-Za-z] // Alphabets
[a-zA-Z._-] // Any of alphabets, ., -, _
{4,8} // repeated 4 to 8 times
[a-zA-Z] // ends with alphabet发布于 2013-09-19 18:17:57
使用单独的regex验证字符串不包含连续字符会更容易:
if(!str.match(/--|\.\.|__/)) {
// passed the test
}(这是JavaScript语法,翻译成您所选择的语言!)
https://stackoverflow.com/questions/18902089
复制相似问题