【问题标题】:get ALL specified substring in powershell在powershell中获取所有指定的子字符串
【发布时间】:2019-11-19 05:43:20
【问题描述】:

我正在尝试获取“子字符串一”和“子字符串二” 我使用的脚本允许我在 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

【问题讨论】:

    标签: regex powershell


    【解决方案1】:
    • 由于您的第一个 &lt;style&gt; 元素跨越两行,您必须打开 SingleLine 正则表达式选项才能使 . 也匹配换行符(换行符)。

    • 要在输入字符串中查找多个匹配项,请使用::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() })
    

    以上产出:

    SubString One
    SubString two 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 2013-03-30
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      相关资源
      最近更新 更多