尝试在以下条件下为字符串(公司/组织名称)构建正则表达式:
正则表达式:/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/
console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('_')); // shouldn't allow
console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('a')); // shouldn't allow
console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('abc abc')); // shouldn't allow
console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('_123')); // works fine
console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('# abc')); // works fine
console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('abc abc!')); // works fine
console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('abc abc# abc')); // works fine
当前的正则表达式不符合所有条件,无法确定正则表达式有什么问题?
答案 0 :(得分:2)
您可以使用
/^(?=.{2})(?!(?:[^_.#&!-]*[_.#&!-]){2})[a-zA-Z0-9_.#&!-]+(?:\s[a-zA-Z0-9_.#&!-]+)*$/
详细信息
^
-字符串的开头(?=.{2})
-任何2个字符必须在开头(?!(?:[^_.#&!-]*[_.#&!-]){2})
-字符串中没有_.#&!-
个字符出现2次[a-zA-Z0-9_.#&-]+
-允许1个或多个字符(空格除外)(?:\s[a-zA-Z0-9_.#&!-]+)*
-0次以上的出现
\s
-1个空格[a-zA-Z0-9_.#&!-]+
-1个以上的字母,数字和一些符号$
-字符串的结尾。JS演示
var rx = /^(?=.{2})(?!(?:[^_.#&!-]*[_.#&!-]){2})[a-zA-Z0-9_.#&!-]+(?:\s[a-zA-Z0-9_.#&!-]+)*$/;
console.log(rx.test('_')); // shouldn't allow
console.log(rx.test('a')); // shouldn't allow
console.log(rx.test('abc abc')); // shouldn't allow
console.log(rx.test('_123')); // works fine
console.log(rx.test('# abc')); // works fine
console.log(rx.test('abc abc!')); // works fine
console.log(rx.test('abc abc# abc')); // works fine