我想你正在寻找这个:
/^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)*$/i
编辑:
这个稍微好一点(受到@HashemQolami?:
和\d
@elclanrs 的启发):
/^[a-z][a-z\d]*(?:\.[a-z][a-z\d]*)*$/i
这个更短,但做同样的工作:
/^[a-z](?:[a-z\d]*(?:\.[a-z])?)*$/i
这个也是,使用前瞻来测试它不以 a 结尾.
:
/^(?!.*\.$)(?:[a-z][a-z\d]*\.?)+$/i
请注意,所选答案不适用于“abc”或在某些情况下超过两个级别。
更新:
我做了一个小(非常基本的)测试:
var valid = [
"com.company.package",
"com.company",
"com.company1",
"com1.company1",
"a.b.c",
"a1.b.c3.d",
"a1.b2.c3.d4"];
var invalid = [
"1com.company.package",
"com.1company",
"com.com%any",
".com.company",
"com.company.",
"com ",
" com",
"",
".",
"com..company"];
function testRegex(regex, list)
{
var res=[];
for(var i=0; i<list.length; i++)
{
if(regex.test(list[i]))
res.push(list[i] + " ==> matched");
else
res.push(list[i] + " ==> NOT matched");
}
return res.join('<br>');
}
var regex = /^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)*$/i;
var html = "<p>VALID</p>";
html += testRegex(regex, valid);
html += "<p>INVALID</p>";
html += testRegex(regex, invalid);
document.write("<div>" + html + "</div>");