Javascript - Regexp每个单词一个大写字母

时间:2016-01-18 06:20:42

标签: javascript jquery regex capitalization

我找不到用以下条件写regexp的方法:

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

正确值的示例:

  • John Adam Ben
  • 狗猫鹦鹉
  • 夹心咖啡饼干
  • 感受到差异

错误值的示例:

  • JOHN ADAM BEN
  • DoG cat PaRRoT
  • SANDWICH cofee Biscuit
  • 费用difference

甚至可以编写上面处理的regexp吗?

提前致谢

5 个答案:

答案 0 :(得分:2)

你可以试试这个,

^(?:[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>';
&#13;
&#13;
&#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

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

答案 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 它匹配这些字符串:

  • JOHN ADAM BEN
  • DoG cat PaRRoT
  • SANDWICH cofee Biscuit
  • 费用difference