PowerShell 从字符串中提取 url

问题描述 投票:0回答:1

我从 Word 文档中检索了所有网址并将其保存到变量中。通过查找 http 关键字来修剪 URL。 但是,当 url 之间存在标题或任何其他文本时,所有文本都会添加到前一个 url 并破坏该 url: 例如:

[https://maven.apache.org/plugins/maven-dependency-plugin/get-mojo.html][1]

Headline
=========
[https://maven.apache.org/plugins/maven-dependency-plugin/get-mojo.html][1]

通过我的源代码,我得到以下 URL/字符串:

[https://maven.apache.org/plugins/maven-dependency-plugin/get-mojo.htmlHeadline][2]

但是,这不是一个有效的网址,我想稍后检查网址的状态代码,但由于无效的网址字符串而没有成功。

$hyperlinks = $x.document.body.innertext         # all text as a single string (no breaks)

$hyperlinks `
  | Select-String -Pattern 'https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)' -AllMatches `
  | % { $_.Matches } `
  | % { $_.Value } `
  | Sort-Object `
  | Get-Unique

$array = $hyperlinks -split '(?=http)'
regex string powershell http url
1个回答
1
投票
$hyperlinks = $x.document.ChildNodes.p.innertext

$hyperlinks = $hyperlinks | Select-String -Pattern '(ftp|ftps|sftp|http|https)://(\S)*' -AllMatches `
  | % { $_.Matches } `
  | % { $_.Value } `
  | Sort-Object `
  | Get-Unique


$array = $hyperlinks | foreach-object { $_ -split '(?=http://)' }
$array = $array | foreach-object { $_ -split '(?=https://)' }
$array = $array | foreach-object { $_ -split '(?=ftp://)' }
$array = $array | foreach-object { $_ -split '(?=sftp://)' }
$array = $array | foreach-object { $_ -split '(?=ftps://)' }

$array = $array | where-object { -not [String]::IsNullOrEmpty($_) }
© www.soinside.com 2019 - 2024. All rights reserved.