gpt4 book ai didi

regex - 在PowerShell中获取所有指定的子字符串

转载 作者:行者123 更新时间:2023-12-03 01:30:12 25 4
gpt4 key购买 nike

我正在尝试获取“子字符串一”和“子字符串二”
我正在使用的脚本允许我在substring之间使用substring,但是:

1)仅第一个子字符串,而不是全部
2)不支持多行,这意味着在上面的示例中我将没有“SubString One”

请帮忙 !

$a = " randomText <style>SubString One
</style>
another randomText <style>SubString two </style>"

$pattern = "<style>(.*?)</style>"

$b = [regex]::Match($a,$pattern).Groups[1].Value

write-host $b

最佳答案

  • 由于您的第一个<style>元素跨越两行,因此必须启用SingleLine regex选项才能使.也匹配换行符(换行符)。
  • 要在输入字符串中找到多个匹配项,请使用::Matches()而不是::Match()方法。
  • $a = " randomText <style>SubString One
    </style>
    another randomText <style>SubString two </style>"

    # Inline option (?s) (SingleLine) makes '.' match newlines.
    $pattern = "(?s)<style>(.*?)</style>"

    # Use ::Matches() and .ForEach() to extract the capture-group match
    # from each match.
    # .Trim() removes surrounding whitespace, notably the newline at the
    # end of 'SubString One'
    [regex]::Matches($a, $pattern).ForEach({ $_.Groups[1].Value.Trim() })

    以上 yield :

    SubString One
    SubString two

    关于regex - 在PowerShell中获取所有指定的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58923099/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com