Nerf D
Nerf D

Reputation: 143

Powershell regex only select digits

I have a script that I am working on to parse each line in the log. My issue is the regex I use matches from src= until space.

I only want the ip address not the src= part. But I do still need to match from src= up to space but in the result only store digits. Below is what I use but it sucks really badly. So any help would be helpful

#example text

$destination=“src=192.168.96.112 dst=192.168.5.22”

$destination -match 'src=[^\s]+'

$result = $matches.Values

#turn it into string since trim doesn’t work

$result=echo $result

$result=$result.trim(“src=”)

Upvotes: 0

Views: 2040

Answers (2)

The fourth bird
The fourth bird

Reputation: 163297

Another way could be using a capturing group:

src=(\S+)

Regex demo | Powershell demo

For example

$destination=“src=192.168.96.112 dst=192.168.5.22”
$pattern = 'src=(\S+)'
Select-String $pattern -input $destination -AllMatches | Foreach-Object {$_.Matches} | Foreach-Object {$_.Groups[1].Value}

Output

192.168.96.112

Or a bit more specific matching the dot and the digits (or see this page for an even more specific match for an ip number)

src=(\d{1,3}(?:\.\d{1,3}){3})

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626802

You can use a lookbehind here, and since -match only returns the first match, you will be able to access the matched value using $matches[0]:

$destination -match '(?<=src=)\S+' | Out-Null
$matches[0]
# => 192.168.96.112

See the .NET regex demo.

  • (?<=src=) - matches a location immediately preceded with src=
  • \S+ - one or more non-whitespace chars.

To extract all these values, use

Select-String '(?<=src=)\S+' -input $destination -AllMatches | Foreach {$_.Matches} | Foreach-Object {$_.Value}

or

Select-String '(?<=src=)\S+' -input $destination -AllMatches | % {$_.Matches} | % {$_.Value}

Upvotes: 1

Related Questions