Regex Experts. I need some help to capture the IP address and its status from the below HTML string.
$html = "<div><br> Active Zone : BW Zone 1[1], VIP = 192.168.254.10</div>
<div><br> <a href=https://192.168.254.10/checkGlobalReplicationTier>https://192.168.254.10/checkGlobalReplicationTier</a>
[ACTIVE]</div>
<div> <a href=https://192.168.254.10/checkReplication>https://192.168.254.10/checkReplication</a></div>
<div><br> <a href=https://192.168.254.11/checkGlobalReplicationTier>https://192.168.254.11/checkGlobalReplicationTier</a>
[STANDBY]</div>
<div> <a href=https://192.168.254.11/checkReplication>https://192.168.254.11/checkReplication</a></div>
<div><br> Local Zones:</div>
<div> LC Zone 3[3], VIP = 192.168.254.13
<div> <a href=https://192.168.254.13/checkReplication>https://192.168.254.13/checkReplication</a>
[ACTIVE]</div>"
[regex]::matches($html, '((\d{1,3}\.){3}\d{1,3})((?s).*?)((?<=\[)[A-z]*(?=\]))').value
The above regex is able to get the IP and Status.. but i want to omit everything in-between the IP and Status. How do i do this with non capturing regex.
192.168.254.10 Active
192.168.254.11 Standby
192.168.254.13 Active
CodePudding user response:
It is general a bad idea to attempt to parse HTML with regular expressions.
Instead use a designated HTML parser as the HtmlDocument Class.
Example
function ParseHtml($String) {
$Unicode = [System.Text.Encoding]::Unicode.GetBytes($String)
$Html = New-Object -Com 'HTMLFile'
if ($Html.PSObject.Methods.Name -Contains 'IHTMLDocument2_Write') {
$Html.IHTMLDocument2_Write($Unicode)
}
else {
$Html.write($Unicode)
}
$Html.Close()
$Html
}
$Document = ParseHtml $Html
$Document.getElementsByTagName('div') |ForEach-Object {
$a = $_.getElementsByTagName('a')
if ($_.lastChild.nodeValue -match '\[(?<Status>ACTIVE|STANDBY)\]') {
$Uri = [Uri]$($_.getElementsByTagName('a')).Host
[pscustomobject]@{
Ip = ([Uri]$($_.getElementsByTagName('a')).href).Host
Status = $Matches.Status
}
}
}
Ip Status
-- ------
192.168.254.10 ACTIVE
192.168.254.11 STANDBY
192.168.254.13 ACTIVE
CodePudding user response:
You may try the following approach:
.*?(\d{1,3}(?:\.\d{1,3}){3})[^\[] \[([A-z] )\].*
and replace by:
$1 $2