regex - 命令行提取文件中引用的所有域名

标签 regex powershell text-extraction

我需要一种方法来在充满URL的文件中提取所有域名(我不在乎完整的URL)。

输入:

<html xmlns:og="http://ogp.me/ns#" xmlns:fb="http://www.facebook.com/2008/fbml" lang="en-US" style="font-size:calc(1em*0.625)" class="hiperf">
<link rel="canonical" href="http://www.msn.com/" />
<link rel="stylesheet" href="http://t-am.s-msn.com/sc/css/87/59a8b7d9f06b8bd9a73fa79c968252.css" media="all" />
<li id="sign-in-out"><a href="https://login.live.com/login.srf?wa=wsignin1.0&amp;rpsnv=12&amp;ct=1406822543&amp;rver=6.1.6195.0&amp;wp=MBI_SSL&amp;wreply=https://login.secure.blu.msn.com/wlsignin.aspx?ru=http%253a%252f%252ft.msn.com%252f&amp;lc=1033&amp;id=1184&amp;pcexp=True">Sign in</a></li>

输出:
ogp.me
www.facebook.com
www.msn.com
t-am.s-msn.com
login.live.com
login.secure.blu.msn.com

例如,此正则表达式匹配可满足我的需要:
    https?:\/\/.*?\/

如何通过命令行完成此操作?

我试过了...
    xidel --extract "https?://{.}/" http://t.msn.com >> testoutput.txt

...但是我的语法不正确。如果xidel不是正确的工具,我愿意使用wget下载页面,然后使用其他方法来解析所有http/s引用。

最佳答案

如果要使用正则表达式,可以执行以下操作:

gc input.html | %{[regex]::matches($_, "https?:\/\/(.*?)\/")} | %{(new-object system.uri $_.value).host}

获取主机名列表。

如果这不够灵活,则可以使用HTML Agility Pack解析HTML并提取hrefs。

如果要删除重复项,可以使用select -uniq:
gc input.html | %{[regex]::matches($_, "https?:\/\/(.*?)\/")} | %{(new-object system.uri $_.value).host} | select -uniq

关于regex - 命令行提取文件中引用的所有域名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25064249/

相关文章:

Python 正则表达式插入符号在多行模式下不起作用?

windows - 如何在 PowerShell 中获取错误的行号

powershell - 在 Powershell 中确定 32/64 位

php - 提取出现在几个禁用字符之一之前的字符

javascript - 如何在不同长度的文本周围创建//的注释 block

javascript - 是否存在允许正则表达式的 JavaScript 的 String.indexOf() 版本?

MySQL正则表达式用于排除字符串

powershell - 这段代码中的[0]在做什么?

pandas - 需要全部提取pandas dataframe中括号内的内容

excel - 使用幂查询按数字字符串的最小长度从文本中提取数字