RegExp“i”不区分大小写VS toLowerCase()(javascript)

时间:2017-12-11 03:38:49

标签: javascript regex pangram

我希望有人可以向我解释为什么我需要使用“toLowerCase()”如果我已经使用了不区分大小写的正则表达式“i”。 练习是一个pangram,可以接受数字和非ascii字符,但字母表中的所有字母必须以小写,大写或混合形式出现。在添加“toLowerCase()”之前,我无法正确解决此练习。这是来自exercism.io的javascript练习之一。以下是我的代码:

var Pangram = function (sentence) {
  this.sentence = sentence;
};

Pangram.prototype.isPangram = function (){
  var alphabet = "abcdefghijklmnopqrstuvwxyz", mustHave = /^[a-z]+$/gi, 
  x = this.sentence.toLowerCase(), isItValid = mustHave.test(x);

  for (var i = 0; i < alphabet.length; i++){
    if (x.indexOf(alphabet[i]) === -1 && isItValid === false){
      return false;
    }

  }
  return true;

};

module.exports = Pangram;

2 个答案:

答案 0 :(得分:2)

正则表达式可能没有做你认为它正在做的事情。这是您的代码评论正在发生的事情:

Pangram.prototype.isPangram = function (){
  var alphabet = "abcdefghijklmnopqrstuvwxyz", mustHave = /^[a-z]+$/gi, 
  x = this.sentence.toLowerCase(), isItValid = mustHave.test(x);

  // for every letter in the alphabet
  for (var i = 0; i < alphabet.length; i++){
    // check the following conditions:
    // letter exists in the sentence (case sensitive)
    // AND sentence contains at least one letter between a-z (start to finish, case insensitive)
    if (x.indexOf(alphabet[i]) === -1 && isItValid === false){
      return false;
    }

  }
  return true;

}

检查每个字母是否存在的逻辑与正则表达式无关,这两个字母用于单独的目的。实际上,根据您对问题的描述,正则表达式会导致您的解决方案在某些情况下失败。例如,假设我们有字符串"abcdefghijklmnopqrstuvwxyz-"。在这种情况下,即使这句话应该返回true,你的正则表达式也会测试为假。

我的建议是删除正则表达式,在句子上使用toLowerCase,并迭代字母表检查句子是否包含每个字母 - 您似乎是您所在的曲目。

以下是一些带有一些测试的示例解决方案。快乐学习!

function isPangram (str) {
  const alphabet = 'abcdefghijklmnopqrstuvwxyz'
  const strChars = new Set(str.toLowerCase().split(''))

  return alphabet.split('').every(char => strChars.has(char))
}

const tests = [
  "abc",
  "abcdefghijklmnopqrstuvwxyz",
  "abcdefghijklmnopqRstuvwxyz",
  "abcdefghijklmnopqRstuvwxyz-",
]

tests.forEach(test => {
  console.log(test, isPangram(test))
})

答案 1 :(得分:1)

这是因为您手动检查小写字母:

if (x.indexOf(alphabet[i]) === -1)

alphabet[i]将是您的字母字符串之一,您已将其定义为小写字母。

看起来你根本不需要正则表达式,或者至少它没有做你认为它正在做的事情。由于你的正则表达式只允许使用字母字符,如果你的句子有任何空格,它将会失败。