【问题标题】:Get filtered array using Regex [closed]使用正则表达式获取过滤数组 [关闭]
【发布时间】:2021-03-25 09:14:35
【问题描述】:

我有如下input 数组。

const input = [
  '_rels', 'item1.xml',
  'item2.xml', 'item3.xml',
  'item4.xml', 'item5.xml',
  'item6.xml', 'item7.xml',
  'itemProps1.xml', 'itemProps2.xml',
  'itemProps3.xml', 'itemProps4.xml',
  'itemProps5.xml', 'itemProps6.xml',
  'itemProps7.xml'
]

数组可以包含任何字符串。

我想过滤item{number}.xml的数组,不包括itemProps{number}.xml

预期的结果是:

const output = [
'item1.xml', 'item2.xml', 'item3.xml', 'item4.xml', 'item5.xml', 'item6.xml', 'item7.xml'
]

【问题讨论】:

  • 为什么是正则表达式?只需搜索itemProps
  • 数组中可能有许多其他非item前缀元素。
  • 然后保留所有以item 开头但不以itemProps 开头的元素。仍然不需要正则表达式。
  • 如果我过滤以item开头的元素,那么itemProps1.xml也将包含在结果中,但我只想item1.xml, item2.xml, ...
  • 你错过了 "... 但不是 itemProps" 我的评论部分

标签: javascript arrays regex


【解决方案1】:

您可以使用RegExp.prototype.test()Array.prototype.filter 方法来获得结果。

 const input = [
  '_rels', 'item1.xml',
  'item2.xml', 'item3.xml',
  'item4.xml', 'item5.xml',
  'item6.xml', 'item7.xml',
  'itemProps1.xml', 'itemProps2.xml',
  'itemProps3.xml', 'itemProps4.xml',
  'itemProps5.xml', 'itemProps6.xml',
  'itemProps7.xml'
];

const res = input.filter(item => /^item\d+\.xml$/i.test(item));

console.log(res);

【讨论】:

    【解决方案2】:

    您可以像这样利用正则表达式与Array.prototype.reduce 方法结合

    const input = [
      '_rels', 'item1.xml',
      'item2.xml', 'item3.xml',
      'item4.xml', 'item5.xml',
      'item6.xml', 'item7.xml',
      'itemProps1.xml', 'itemProps2.xml',
      'itemProps3.xml', 'itemProps4.xml',
      'itemProps5.xml', 'itemProps6.xml',
      'itemProps7.xml'
    ]
    const regExPattern = /itemProps\d+\.xml/
    const result = input.reduce((acc, current) => {
      if(regExPattern.test(current) === false){
        return acc.concat(current);
      }
      return acc;
    }, []);
    
    console.log(result);

    【讨论】:

    • 这只是 Sajeebs .filter() 答案的复杂版本(而且还缺少 _rels 条目)
    • 我做了更改,只接受以item 开头并包含任意数量的数字后跟.xml 的项目
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    • 2011-04-17
    • 2013-03-08
    • 2013-06-25
    • 1970-01-01
    相关资源
    最近更新 更多