2011-11-02 232 views

回答

2

这会工作:

/^[a-z][a-z0-9_]{0,7}$/i 

例如,

/^[a-z][a-z0-9_]{0,7}$/i.test('a1234567'); // true 
/^[a-z][a-z0-9_]{0,7}$/i.test(''); // false 
+0

这看起来不错,谢谢。 – user428747

+0

如下所述:'[a-z] {1}'是不必要的。而且,你的测试是错误的,并且会匹配任意数量的前导字母,因为'{1,}'将匹配无限字母。因此,例如:'/^[az] {1,} [a-z0-9 _] {0,7} $/i.test(“aaaa0909090”); // true'不是您想要的,因为测试字符串长度为11个字符(不是8,如指定的那样)。 – Jesse

+0

@Jesse,谢谢,那些错误。固定 – Joe

1

尝试了这一点:

/^[A-Za-z]{1}[a-zA-Z0-9_]{0,7}$/ 
+3

'{1}'是多余的;它始终默认为1. – poke

+0

这需要字符串中至少有2个字符。它不符合'a'。 –

+0

@JonathanM我修好了。 – Neal

1

试试这个:

/^[a-zA-Z][0-9a-zA-Z_]{0,7}$/ 

这需要一个字母开始字符,并且可以允许多达7个以上的字母,可以是字母数字或下划线。

编辑:谢谢,杰西的纠正。

2

\w简写为所有字母,数字和下划线。 [A-Za-z]是矫枉过正,/i国旗会让你所有的字母,不区分大小写。

因此,您所需要的一个超级简单的正则表达式是:

/^[a-z]\w{0,7}$/i

/^[a-z]\w{0,7}$/i.test("a1234567"); 
> true 
/^[a-z]\w{0,7}$/i.test("a12345697"); 
> false 
/^[a-z]\w{0,7}$/i.test(""); 
> false 
+0

另一个说明,没有'i'标志,Jonathan M的'[az]'不会匹配大写字母,Neal的'[a-zA-z]'不会匹配大写字母(实际上不确定混合大小写会做什么,但可能不是你想要的),而IAbstractDownVoteFactor的'[az] {1}'是多余的,'[az]'将总是匹配单个字符,总是不需要{1}'。保持你的正则表达式简单易读! – Jesse

+0

+1,用'\ w'调用好。 –

+0

这是错误的,因为它包含数字... – FailedDev

0

而另一版本向前看符号:)

if (subject.match(/^(?=[a-z]\w{0,7}$)/i)) { 
    // Successful match 
} 

说明:

"^" +   // Assert position at the beginning of the string 
"(?=" +   // Assert that the regex below can be matched, starting at this position (positive lookahead) 
    "[a-z]" +  // Match a single character in the range between “a” and “z” 
    "\\w" +   // Match a single character that is a “word character” (letters, digits, etc.) 
     "{0,7}" +  // Between zero and 7 times, as many times as possible, giving back as needed (greedy) 
    "$" +   // Assert position at the end of the string (or before the line break at the end of the string, if any) 
")" 
+0

Upvote多样性和原创性,downvote复杂性和可读性。非常有趣,但。 :) –

相关问题