我在powershell中使用正则表达式遇到了一点问题。我的正则表达式只适用于一行文本,而我需要处理多行文本。
例如HTML:
<li> test </li>
</ul>
我希望正则表达式可以匹配所有内容,包括"/ul>"。我的建议是:
'(^.*<li>.*</ul>)'
但它不起作用。这是否可能?谢谢。
我在powershell中使用正则表达式遇到了一点问题。我的正则表达式只适用于一行文本,而我需要处理多行文本。
例如HTML:
<li> test </li>
</ul>
'(^.*<li>.*</ul>)'
这取决于您使用的正则表达式方法。
如果您使用.NET的Regex::Match
,那么有第三个参数可以定义额外的regex
选项。在这里使用[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 命令,您需要在您的正则表达式中指定单行选项(?s)
:$html =
@'
<li> test </li>
</ul>
'@
$regex = '(?s)(^.*<li>.*\</ul>)'
$html | Select-String $regex -AllMatches | Select -Expand Matches | select -expand Value
使用多行单行正则表达式,带有-match
:
$string = @'
notmached
<li> test </li>
</ul>
notmatched
'@
$regex = @'
(?ms)(<li>.*</li>.*?
\s*</ul>)
'@
$string -match $regex > $null
$matches[1]
<li> test </li>
</ul>