【问题标题】:REGEX for multiple lines - powershell多行的正则表达式 - powershell
【发布时间】:2015-08-10 20:33:55
【问题描述】:

powershell 中的正则表达式有点问题。我的 REGEX 仅适用于一行。我需要在多行上工作。

例如html:

<li> test </li>
</ul>

我希望 REGEX 获取所有内容,包括“/ul>”。我的建议是:

'(^.*<li>.*</ul>)' 

但它不起作用。甚至可能吗?谢谢。

【问题讨论】:

标签: regex powershell


【解决方案1】:

取决于您使用的正则表达式方法。

如果您使用 .NET Regex::Match,还有第三个参数,您可以在其中定义额外的 regexoptions。在这里使用[System.Text.RegularExpressions.RegexOptions]::Singleline

$html = 
@'
<li> test </li>
</ul>
'@

$regex = '(^.*<li>.*\</ul>)' 

[regex]::Match($html,$regex,[System.Text.RegularExpressions.RegexOptions]::Singleline).Groups[0].Value

如果您想使用Select-String cmdlet,您必须在regex 中指定单行选项(?s)

$html = 
@'
<li> test </li>
</ul>
'@

$regex = '(?s)(^.*<li>.*\</ul>)' 

$html | Select-String $regex -AllMatches | Select -Expand Matches | select -expand Value

【讨论】:

    【解决方案2】:

    使用多行单行正则表达式,带有-match

    $string = @'
    notmached
    <li> test </li>
    </ul>
    notmatched
    '@
    
    
    $regex = @'
    (?ms)(<li>.*</li>.*?
    \s*</ul>)
    '@
    
    $string -match $regex > $null
    $matches[1]
    
    <li> test </li>
    </ul>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多