REGEX for multiple lines - powershell
I have a little problem with regex in powershell. My REGEX only works for one line. I need to work on multiple lines.
For example html:
<li> test </li>
</ul>
I want REGEX to take everything including "/ ul>". My suggestion:
'(^.*<li>.*</ul>)'
But it doesn't work. Is it possible? Thank.
It depends on which regex method you are using.
If you are using .NET Regex::Match
there is a third parameter where you can define additional options regex
. Use [System.Text.RegularExpressions.RegexOptions]::Singleline
here:
$html =
@'
<li> test </li>
</ul>
'@
$regex = '(^.*<li>.*\</ul>)'
[regex]::Match($html,$regex,[System.Text.RegularExpressions.RegexOptions]::Singleline).Groups[0].Value
If you want to use the Select-String cmdlet , you need to specify the singleline option (?s)
in your regex
:
$html =
@'
<li> test </li>
</ul>
'@
$regex = '(?s)(^.*<li>.*\</ul>)'
$html | Select-String $regex -AllMatches | Select -Expand Matches | select -expand Value
Using a multi-line one-line regex with -match
:
$string = @'
notmached
<li> test </li>
</ul>
notmatched
'@
$regex = @'
(?ms)(<li>.*</li>.*?
\s*</ul>)
'@
$string -match $regex > $null
$matches[1]
<li> test </li>
</ul>