首页 > 解决方案 > 在字符串中的 Y 索引处查找 X 字符并使用此信息过滤数组

问题描述

我有一个字符串和一个字符串数组。字符串示例如下:

let example1 = "_a_t_";
let example2 = "N_l_:t___";
let example3 = "B__z_l";

我们可以看到,字符串有 Z 个字符长,并且得到了随机数量的非 _ 字符。字符串永远不会只有 _ 也不会没有下划线。

let array = ["Walts", "Grate", "Ralts", "Names"];

如果我们使用 example1 字符串和上面的数组,我想过滤数组,结果变成:

let newArray = ["Walts", "Ralts"];

基本上,在已知字符中,我想使用它们及其位置来过滤数组。目前我已经找到了如何找到第一个字符并使用它来过滤数组。这就是这样做的:

let example1 = "_a_t_";
let array = ["Walts", "Grate", "Ralts", "Names"];

let charIndex = example1.match("[a-zA-Z]").index;
/*Currently using the RegEx [a-zA-Z], but this should be changed to include all characters 
besides underscores but I don't know what to put in between the square brackets*/
let firstChar = example1.charAt(charIndex);

let filteredArray = array.filter(function (element) {
  return element.charAt(charIndex) === firstChar;
});

console.log(filteredArray); //this returns ["Walts", "Ralts", "Names"]

我在这里卡住了。如果字符串中有多个显示的字符,我不知道该怎么做。经过一番思考,对我来说合乎逻辑的事情是以某种方式计算所有不是下划线的字符,然后使用它,进行循环。循环将找到每个字符及其索引,然后过滤数组。当数组被完全过滤时,循环将结束。使用上面的数组和example1字符串,希望的目标是得到["Walts", "Ralts"].

我认为问题得到了彻底的解释,最终目标也很明确。这是我第一次在 Stack Overflow 上发帖,所以我很兴奋。

标签: javascriptstring

解决方案


我认为如果您从每个模式创建一个正则表达式并仅针对整个模式测试每个字符串,这可能会更容易。这是概念实施的快速证明。

它只是在创建表达式时替换_.,因此下划线将匹配任何字符,然后根据字符串是否匹配过滤数组。

例如,字符串"_a_t_"成为/^.a.t.$/gi匹配 Walts 和 Ralts 但不匹配 Grate 或 Names 的正则表达式。

正则表达式模式/^.a.t.$/gi松散地转换为:

  • ^字符串的开头
  • .后跟任何字符
  • a后跟文字'a'
  • .后跟任何字符
  • t后跟文字't'
  • .后跟任何字符
  • $字符串的结尾。

const example1 = "_a_t_";
const example2 = "N_l_:t___";
const example3 = "B__z_l";
const array = ["Walts", "Grate", "Ralts", "Names"];

// turn the string patterns into regular expressions
const regexes = [example1, example2, example3].map(pattern => {
  return new RegExp(`^${pattern.replaceAll('_', '.')}$`, 'i');
});

// filter out names that don't match any of the expressions
const result = array.filter(name => regexes.some(r => r.test(name)));
  
console.log(result);

编辑:更新以简化示例实现。


推荐阅读