MrMr
MrMr

Reputation: 493

PowerShell Regular Expression Match IP Not Proceeded and Not Followed by IP

I'm attempting to use the match operator in PowerShell to find IP addresses that are not proceeded and not followed by an IP. My goal is to capture just IP's and NOT the IP's that are followed by subnet masks. Also, I used get content on a text file and then did a for each through it using the match at each line.

This is what I have so far and I don't appear to be getting the correct results:

(?<!\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?!\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})

Example data:

10.0.0.1

word 11.11.11.11

word 12.12.12.12 255.255.255.0

15.15.15.15 255.255.255.0

Expected Matches:

10.0.0.1

11.11.11.11

Upvotes: 1

Views: 1394

Answers (2)

mjolinor
mjolinor

Reputation: 68243

One way to simplify the task is to use chained operators:

$Lines = Get-Content $file
@($Lines) -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' -notmatch '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' -replace '.+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).+','$1'

Using the operators this way causes them to act as filters, so the -match operator will filter out all lines that don't contain an IP address at all, then the -notmatch will filter out the ones that also contain a following subnet mask, and finally the -replace operator will extract the IP address from the lines that passed both tests.

Upvotes: 2

briantist
briantist

Reputation: 47772

Regex isn't always the answer.

$IPs = $line.Split().Where({$_ -as [IPAddress]})
if ($IPs.Count -eq 1) {
    $match = $IPs[0]
}

What this does

$line represents the current line.

First, split it into an array (the .Split() method splits on whitespace by default), then filter the array with .Where() to only include elements that can be succesfully cast to an [IPAddress]. That gives you an array of all the IP addresses in the line.

After that, test that the count is 1, so you only proceed when it found a single IP address.

Upvotes: 4

Related Questions