首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何通过正则表达式统计http:// adresses列表中的所有域名?

如何通过正则表达式统计http:// adresses列表中的所有域名?
EN

Stack Overflow用户
提问于 2018-06-03 18:40:09
回答 2查看 50关注 0票数 -1

因此,我有一个http:// adresesses列表,并且我需要在JS中使用正则表达式对域名进行计数。我不知道如何做到这一点,因为他们有不同的长度,有些是相似的。我怎样才能做到这一点呢?正则表达式是我的噩梦。here is my list

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-06-04 17:16:23

使用此线程What is a good regular expression to match a URL?中修改的正则表达式,您可以计算匹配的数量,如下所示:

代码语言:javascript
复制
// Your original list of addresses
const data = `
http://www.gaba.ch/fr_CH/519/Netuschil-L-et-al-Eur-J-Oral-Sci-103-1995-355-361.htm?Subnav2=ResearchProducts&Article=17516
http://www.gaba.fi/fi_FI/725/Suche.htm?Page=42
http://www.gaba.ch/fr_CH/538/Recomend-Page.htm?LinkID=576&Brand=meridolHalitosis&Subnav=&Product=312435
http://www.gaba.com/en/1071/Professor-Edwin-G-Winkel.htm
http://www.gaba.ch/fr_CH/580/Congress-Calendar.htm?CongressId=289461&Page=6
// ... etc
`;

// Make sure you include the g flag to find all the matches and not just one
const addresses = data.match(/https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b(?:[-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);

// Get length of the matched array
// - In this example: 5
// - In your case: 4815
const addressesCount = addresses.length;

编辑:

根据你的评论,我对代码做了一些调整:

代码语言:javascript
复制
// Your original list of addresses
const data = `
http://www.gaba.ch/fr_CH/519/Netuschil-L-et-al-Eur-J-Oral-Sci-103-1995-355-361.htm?Subnav2=ResearchProducts&Article=17516
http://www.gaba.fi/fi_FI/725/Suche.htm?Page=42
http://www.gaba.ch/fr_CH/538/Recomend-Page.htm?LinkID=576&Brand=meridolHalitosis&Subnav=&Product=312435
http://www.gaba.com/en/1071/Professor-Edwin-G-Winkel.htm
http://www.gaba.ch/fr_CH/580/Congress-Calendar.htm?CongressId=289461&Page=6
// ... etc
`;

// Find all valid domains (excluding http and www)
const addresses = data.match(/https?:\/\/(?:www)?\.((?:.+?)\.[\w\.]{2,5})/g);

// Filter the addresses to only unique ones
const unique = addresses.reduce((acc, cur) => acc.indexOf(cur) > -1 ? acc : acc.concat(cur), []);

// Get number of unique addresses found
// - In this example: 3
// - In your case: 28
const length = unique.length;

注意:像这样的http:/www.bnf.org/bnf/bnf/54/%3C地址将不会匹配,因为它们无效。

票数 0
EN

Stack Overflow用户

发布于 2018-06-03 18:59:01

您可以使用String.prototype.match()方法。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50665476

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档