首页 > 解决方案 > 我需要一个正则表达式来检查数组的当前索引是否存在于特定的数字范围内

问题描述

我知道这里有很多关于正则表达式的信息,但我似乎真的无法让它发挥作用。我有一个 for 循环,循环遍历一个数组。我想看看数组的当前索引是否不等于一组数字(32-64)。我已经声明了一个变量let patt,它包含我认为应该工作的正则表达式,但我无法弄清楚检查它的语法。我确信它会是.match,但再次,不知道如何措辞!.match

任何建议,解决方案,甚至是一个好的 JS 正则表达式教程方向的一点都将不胜感激!

class ShiftCipher{
    constructor(shift){
      this.shift = shift;
    }
    encrypt(string){
      let up = string.toUpperCase();   //convert string to uppercase
      let uni = [];
      let newArr = [];
      let i, j;
      let patt = /[32-64]/g;            //think this is wrong...

      for(i = 0; i < up.length; i++){
        uni.push(up.charCodeAt(i))      //push converted chars as unicodes to new array
        if(uni[i] != 32){              // if unicode is 32 (space) leave as is.  //I want a regex here for != unicode 32 - 64
          uni[i] += this.shift;        // shift unicode by parent class specification (shift)
      }
    }
      for(j = 0; j < up.length; j++){
        if(uni[j] > 90){            // if unicode is higher than 90(z)..
          uni[j] -= 26;             // loop back round starting at (a).
      }
      let text = String.fromCharCode(uni[j]); //convert from unicode to string
      newArr.push(text);                       //push string to array
    }
    
    let final = newArr.join('');      //join array elements(as a string) and store in final
    console.log(final);               
  }
}
  
  const cipher = new ShiftCipher(2);
  cipher.encrypt('I love to code z!');

标签: javascriptregex

解决方案


我想看看数组的当前索引是否不等于一组数字(32-64)

字符代码数字。尝试数值比较。

for (i = 0; i < up.length; i++) {
  if (up.charCodeAt(i) >= 32 && up.charCodeAt(i) <= 64) {
    // ...
  }
}

但从技术上讲,您也可以使用正则表达式。从字符代码创建字符范围的工作方式如下:

var patt = /[\x20-\x40]/;   // hex 20 = decimal 32, hex 40 == decimal 64

for (i = 0; i < up.length; i++) {
  if (patt.test(up.charAt(i)) {
    // ...
  }
}

请注意,这使用.charAt().

/[\x20-\x40]/解释为好像您已经编写了实际字符,因此在这种情况下它相当于/[ -@]/.


推荐阅读