我找不到用以下条件写regexp的方法:
正确值的示例:
错误值的示例:
甚至可以编写上面处理的regexp吗?
提前致谢
答案 0 :(得分:2)
你可以试试这个,
^(?:[A-Z][a-z]*|[a-z]+)(?:\s+(?:[A-Z][a-z]*|[a-z]+))*$
var arr = ["John Adam Ben", "Dog cat parrot", "sandwich coffee Biscuit", "feel the difference", "JOHN ADAM BEN", "DoG cat PaRRoT", "SANDWICH cofee Biscuit", "feeL the diFFerence"];
var regex = /^(?:[A-Z][a-z]*|[a-z]+)(?:\s+(?:[A-Z][a-z]*|[a-z]+))*$/g;
var result = {};
arr.forEach(function(str) {
result[str] = regex.test(str);
regex.lastIndex = 0;
});
console.log(result);
document.body.innerHTML = '<pre>' + JSON.stringify(result, 0, 4) + '</pre>';
&#13;
答案 1 :(得分:1)
尝试使用if
条件,逻辑非运算符!
,RegExp
/([A-Z])(?=[A-Z]+)/g
匹配大写字母后跟大写字母RegExp.prototype.test()
if (!/([A-Z])(?=[A-Z]+)/g.test(str)) {
// do stuff
}
<强>演示:强>
var arr = ["John Adam Ben", "Dog cat parrot", "sandwich coffee Biscuit", "feel the difference", "JOHN ADAM BEN", "DoG cat PaRRoT", "SANDWICH cofee Biscuit", "feeL the diFFerence"];
var regex = /([A-Z])(?=[A-Z]+)/g;
var result = {};
arr.forEach(function(str) {
result[str] = !regex.test(str);
regex.lastIndex = 0;
});
console.log(result);
document.body.innerHTML = '<pre>' + JSON.stringify(result, 0, 4) + '</pre>';
答案 2 :(得分:0)
这个简单的正则表达式应该适合你:
/^(\b[a-z]*[A-Za-z][a-z]*\b\s*)+$/gm
var arr = ["John Adam Ben", "Dog cat parrot", "sandwich coffee Biscuit", "feel the difference", "JOHN ADAM BEN", "DoG cat PaRRoT", "SANDWICH cofee Biscuit", "feeL the diFFerence"];
var regex = /^(\b[a-z]*[A-Za-z][a-z]*\b\s*)+$/g;
var result = {};
arr.forEach(function(str) {
result[str] = regex.test(str);
regex.lastIndex = 0;
});
console.log(result);
document.body.innerHTML = '<pre>' + JSON.stringify(result, 0, 4) + '</pre>';
答案 3 :(得分:0)
$(document).ready(function () {
var test = ["John Adam Ben",
"Dog cat parrot",
"sandwich coffee Biscuit",
"feel the difference",
"JOHN ADAM BEN",
"DoG cat PaRRoT",
"SANDWICH cofee Biscuit",
"feeL the diFFerence"
];
for (i = 0; i < test.length; i++) {
if (/^(\b[a-z]*[A-Za-z][a-z]*\b\s*)+$/g.test(test[i])) {
alert(test[i] + " true")
}
else {
alert(test[i] + " false")
}
}
});
答案 4 :(得分:0)
而不是找到这个:
您可以找到上述不正确的规则。这是:
[^b][A-Z]
您可以在此处测试:https://regex101.com/#javascript 它匹配这些字符串: