【问题标题】:A regex to test if all words are title-case [duplicate]一个正则表达式来测试所有单词是否都是标题大小写[重复]
【发布时间】:2016-11-12 02:05:30
【问题描述】:

我正在尝试提出一个正则表达式来验证以下内容是否正确:

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. 重复上述操作一次或多次

我的想法有什么问题?

【问题讨论】:

  • 你能贴出你的javascript代码吗?
  • 我相信您的正则表达式只是匹配任何包含一个或多个 Title Case 单词的字符串。在开头添加 ^ 并在末尾添加 $ 应该可以解决此问题。
  • /^\s*(?:\s*[A-Z][a-z]*\s*\b)+\s*$/ RegEx101
  • @ETHproductions,你应该把它作为答案而不是评论,因为你是对的。
  • 投反对票,真的吗?

标签: javascript regex


【解决方案1】:

我的想法有什么问题?

您会找到一系列标题大小写的单词,但这不会发现有非标题大小写的单词的情况。

您可以使用简单的正则表达式测试整个输入是否不是标题大小写:

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

如果您真的想检查输入 标题大小写,那么您需要从头到尾匹配字符串,如评论中所述(即“锚定”正则表达式):

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

什么是标题大小写?

但是,严格来说,冠词、连词和介词不是大写的,除非它们以标题开头。因此,更好的测试是:

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

【讨论】:

    【解决方案2】:

    如果你只想知道一个字符串是否匹配条件,而不关心它在哪里失败,你可以检查字符串开头的小写字母,或者空格后面的小写字母:

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

    【讨论】:

      【解决方案3】:

      我的猜测是您忘记在末尾包含全局匹配符号g

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

      尝试这样做:

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

      【讨论】:

      • 这将找到所有标题大小写单词的连续序列,但它如何让您知道有非标题大小写单词?
      猜你喜欢
      • 2016-07-04
      • 1970-01-01
      • 2020-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-14
      • 1970-01-01
      相关资源
      最近更新 更多