使用正则表达式检查字符串错误中的pangram

罗伊想提高自己的编程比赛打字速度。他的朋友建议他重复输入“快速的棕色狐狸跳过懒狗”的句子。该句子被称为pangram,因为它包含字母表中的每个字母。      在多次键入句子后,Roy厌倦了它,因此他开始寻找其他的人物。      给定一个句子,请确定它是否是Pangram。忽略大小写。      如果输入字符串是Pangram,则应返回字符串pangram。否则,它不应返回pangram。

样本输入

我们迅速判定古董象牙带扣获得下一个奖项

// pangram

我们迅速判断了古董象牙带扣的价格

//不是pangram(缺少字母x)

function pangrams(s) {

   const exp = /[a-z]/gi; 

   if(s.includes(exp)){return 'pangram'} else {return 'not pangram'} 
   
}

TypeError:String.prototype.includes的第一个参数不能为正则表达式

如果我正确解决了问题,如何在仍然可以使用正则表达式的情况下解决此问题?

评论
  • svero
    svero 回复

    Your regular expression is wrong. It will only check if the string contains one letter from a to z. You also aren't testing it properly - String.prototype.includes checks for substrings being included in the larger string, not for regular expression validation.

    If you want to test whether a regular expression matches a string, use .test. To check that all letters exist in a string with a regular expression, you'll have to repeat (?=.*a) for every character, eg:

    const pattern = /^(?=.*a)(?=.*b)(?=.*c)(?=.*d)(?=.*e)...../i;
    return s.test(pattern);
    

    但这确实很丑陋且重复。

    I don't think a regular expression is the way to go here. Consider iterating over character codes to get the characters from A to Z and using .includes instead:

    const test = (str) => {
      const strUpper = str.toUpperCase();
      // start at A
      for (let i = 65; i <= 90; i++) {
        if (!strUpper.includes(String.fromCharCode(i))) {
          return false;
        }
      }
      return true;
    };
    console.log(test('The quick brown fox jumps over the lazy dog'));
    console.log(test('The quick brown fox jumps over the lazy do'));

    如果必须使用正则表达式,则可以通过遍历所有字符代码来动态构造它:

    const test = (str) => {
      const pattern = new RegExp(
        '^' +
        Array.from(
          { length: 26 },
          (_, i) => `(?=.*${String.fromCharCode(i + 65)})`
        ).join(''),
        'i'
      );
      return pattern.test(str);
    };
    console.log(test('The quick brown fox jumps over the lazy dog'));
    console.log(test('The quick brown fox jumps over the lazy do'));
  • wet
    wet 回复

    我不会在这里使用正则表达式,因为它可能不是最佳解决方案。而是考虑将输入字符串转换为字母映射,然后断言存在26个键:

    var letters = {};
    var input = "The quick brown fox jumps over the lazy dog";
    input = input.replace(/[^A-Za-z]+/g, "");
    for (var i=0; i < input.length; i++) {
        letters[input.charAt(i).toLowerCase()] = 1;
    }
    
    if (Object.keys(letters).length == 26)
        console.log("PANGRAM");
    else
        console.log("NOT A PANGRAM");