Javascript - 正则表达式每个单词一个大写字母

Javascript - Regexp one capital letter per word

我找不到写符合以下条件的正则表达式的方法:

正确值示例:

错误值示例:

甚至可以编写上面处理的正则表达式吗?

提前致谢

你可以试试这个,

^(?:[A-Z][a-z]*|[a-z]+)(?:\s+(?:[A-Z][a-z]*|[a-z]+))*$

DEMO

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>';

尝试使用 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>';

这个简单的正则表达式应该适合你:

/^(\b[a-z]*[A-Za-z][a-z]*\b\s*)+$/gm

RegEx Demo

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>';

 $(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")
         }
     }

});

而不是找到这个:

  • 每个单词只有一个大写字母(不需要)(理想情况下,如果是 第一个字符)
  • 其余字母必须小写

您可以找到上面不正确的规则。这是:

[^b][A-Z]

你可以在这里测试:https://regex101.com/#javascript 它匹配这些字符串:

  • 约翰·亚当·本
  • DoG 猫 PaRRoT
  • 三明治咖啡饼干
  • 感受差异