正则表达式,用于测试所有单词是否为标题大小写

时间:2016-11-12 02:05:30

标签: javascript regex

我试图想出一个正则表达式来验证以下内容是真的:

This Is A Cat

但是,要评估以下内容是错误的:

This is a cat

或者这也是假的:

This Is A cat (Note the 'c' is not upper case in Cat)

我尝试使用JavaScript,认为以下内容应该有效:

/(\b[A-Z][a-z]*\s*\b)+/

这是我的逻辑:

  1. 从单词边界开始
  2. 匹配大写字符
  3. 匹配零个或多个小写字符
  4. 匹配零个或多个空格
  5. 匹配单词边界
  6. 重复上述一次或多次
  7. 我的想法有什么问题?

3 个答案:

答案 0 :(得分:1)

What is wrong with my thinking?

You're finding a sequence of title-cased words, but that won't pick up cases where there are non-title-cased words.

You can test if the entire input is not title case with the simple regexp:

const tests = ['This Is A Cat', 'This is a cat', 'This Is A cat'];

// Is there any occurrence of a word break followed by lower case?
const re = /\b[a-z]/;

tests.forEach(test => console.log(test, "is not title case:", re.test(test)));

If you really want to check that the input is title case, then you'll need to match the string from beginning to end, as mentioned in a comment (i.e., "anchor" the regex):

const tests = ['This Is A Cat', 'This is a cat', 'This Is A cat'];

// Is the entire string a sequence of an upper case letter,
// followed by other letters and then spaces?
const re = /^\s*([A-Z]\w*\s*)*$/;

tests.forEach(test => console.log(test, "is title case:", re.test(test)));

What is title case?

Strictly speaking, however, articles, conjunctions, and prepositions are not upper-cased unless they start the title. Therefore, a better test would be:

const re = /^\s*[A-Z]\w*\s*(a|an|the|and|but|or|on|in|with|([A-Z]\w*)\s*)*$/;

答案 1 :(得分:0)

我的猜测是你忘了在最后加入全球匹配标志g

  

g 查找所有匹配项,而不是在第一次匹配后停止

尝试这样做:

/(\b[A-Z][a-z]*\s*\b)+/g

答案 2 :(得分:0)

如果您只想知道字符串是否与条件匹配,并且不关心它失败的地方,您可以检查字符串开头的小写字母或后面的小写字母空间:



var str = 'This Is A Cat';
if (str.match(/\b[a-z]/)) {
  console.log('Not Title Case');
}

var str2 = 'This is A Cat';
if (str2.match(/\b[a-z]/)) {
   console.log('Example 2 Is Not Title Case');
}

var str3 = 'this Is A Cat';
if (str3.match(/\b[a-z]/)) {
   console.log('Example 3 Is Not Title Case');
}