通过正则表达式从 return 数据 HTML 中删除所有重复行

Remove all duplicate lines from return data HTML by regex

我在 app script 中使用 regex 从网站抓取数据:

我试试这个代码:

const name = /(?<=<span class="(.*?)">)(.*?)(?=<\/span>)/gi; // work Great

for(var i = 0; i < 9; i++){

var names = data[i].match(name)[0];
Logger.log(names)
}

这段代码工作正常,但给我重复的行:

1:56:22 PM  Notice  Execution started
1:56:35 PM  Info    john
1:56:35 PM  Info    ara
1:56:35 PM  Info    john
1:56:35 PM  Info    anita
1:56:35 PM  Info    ara
1:56:35 PM  Info    fabian
1:56:35 PM  Info    ara
1:56:35 PM  Info    john
1:56:35 PM  Info    fabian
1:56:37 PM  Notice  Execution completed

我想删除所有重复的名称并查看这样的结果:

1:56:22 PM  Notice  Execution started
1:56:35 PM  Info    john
1:56:35 PM  Info    ara
1:56:35 PM  Info    anita
1:56:35 PM  Info    fabian
1:56:37 PM  Notice  Execution completed

设置

您可以使用集合 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) 来完成此操作。

names = Array.from(new Set(names));

我们没有您的最终目标,在这里您只需 console.log 您的数据,但您可能不需要将您的 Set 转换回数组 :)

排序

另一种解决方案是对数组进行排序,然后对其进行迭代,以便更轻松地删除重复项。

array.sort();

array.filter((el, index) => index < array.length && el !== array[index + 1]);

在我的浏览器上测试::

let a = [1,1,2,3,4,4,5,6,7,7];

a.filter((el, index) => index < a.length && el !== a[index + 1]);

Array(7) [ 1, 2, 3, 4, 5, 6, 7 ];

这个解决方案显然不保留任何顺序,而第一个似乎保留初始顺序,至少在我的 firefox 的 js 上是这样

描述

首先我会收集数组中的所有名称。然后使用 [...new Set()] 创建一个唯一名称数组。

脚本

function spanTest() {
  try {
    const name = /(?<=<span class="(.*?)">)(.*?)(?=<\/span>)/gi; // work Great
    let data = ['<=<span class="test">john</span>',
                '<=<span class="test">ara</span>',
                '<=<span class="test">john</span>',
                '<=<span class="test">anita</span>',
                '<=<span class="test">ara</span>',
                '<=<span class="test">fabian</span>',
                '<=<span class="test">ara</span>',
                '<=<span class="test">john</span>',
                '<=<span class="test">fabian</span>'];

    let names = [...new Set(data.map( span => span.match(name)[0]) )];
    console.log(names);
    
  }
  catch(err) {
    console.log(err);
  }
}

7:39:23 AM  Notice  Execution started
7:39:23 AM  Info    [ 'john', 'ara', 'anita', 'fabian' ]
7:39:23 AM  Notice  Execution completed

参考