【问题标题】:PowerShell RegEx match all possible matchesPowerShell RegEx 匹配所有可能的匹配项
【发布时间】:2015-11-28 10:59:42
【问题描述】:

我有以下脚本,其中包含一些正则表达式来捕获此站点上的特定信息。

$Top40Response = Invoke-WebRequest -UseBasicParsing -Uri 'https://www.radioinfo.com.au/knowledge/chart'

$Top40Response.Content -match '<td\Wclass="twRank">[\s\S]+artist">([^<]*)'
$matches

这是匹配最后一个“艺术家”。我想要做的就是让它贯穿并匹配此页面上的每个艺术家,从上到下。

【问题讨论】:

    标签: regex powershell


    【解决方案1】:

    PowerShell 的 -match 只返回第一个匹配项。您必须将Select-String-AllMatches 参数或[regex]::Matches 一起使用。

    Select-String:

    $Top40Response = Invoke-WebRequest -UseBasicParsing -Uri 'https://www.radioinfo.com.au/knowledge/chart'
    
    $Top40Response.Content |
        Select-String -Pattern '<td\s+class="artist">(.*?)<\/td>' -AllMatches |
            ForEach-Object {$_.Matches} |
                ForEach-Object {$_.Groups[1].Value}
    

    [regex]::Matches:

    $Top40Response = Invoke-WebRequest -UseBasicParsing -Uri 'https://www.radioinfo.com.au/knowledge/chart'
    
    $Top40Response.Content |
        ForEach-Object {[regex]::Matches($_, '<td\s+class="artist">(.*?)<\/td>')} |
            ForEach-Object {$_.Groups[1].value}
    

    【讨论】:

    • 太好了,我喜欢使用 select-string 和 -AllMatches 选项
    猜你喜欢
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    相关资源
    最近更新 更多