JoeRod
JoeRod

Reputation: 921

Remove first octet from IP address with Regex split

I'm trying to remove the first octet including the leading . from an IP address, I'm trying to use Regex but I cannot figure out the proper way to use it. Here is my code

'47.172.99.12' -split '\.(.*)',""

The result I want is

172.99.12

Upvotes: 1

Views: 3024

Answers (4)

Matt
Matt

Reputation: 46690

I'm surprised, given the context, that no one mentioned the [ipaddress] class for this. Using this approach also ensures that the string is a valid IP Address.

$ipAddress = "192.168.0.1" -as [ipaddress]
If($ipAddress){
    ($ipAddress.GetAddressBytes())[1..3] -join "."
} Else {
    Write-Host "Invalid Address"
}

-as will attempt to convert the string to [ipaddress]. If successful the cast is performed else $null is returned. Then we use .GetAddressBytes() to break the IP address into its 4 parts. Since we know at this point it is a valid IP then we can safely rejoin the last 3 parts with a period.

Upvotes: 2

user2555451
user2555451

Reputation:

The . character has a special meaning in a Regex pattern: it matches any character except a newline. You will need to escape it in order to match a literal period:

'47.172.99.12' -split '\.(.*)',""
                       ^

Note however that this will return more results than you need:

PS > '47.172.99.12' -split '\.(.*)',""
47
172.99.12

PS >

To get what you want, you can index the result at 1:

PS > ('47.172.99.12' -split '\.(.*)',"")[1]
172.99.12
PS >

That said, using Regex for this task is somewhat overkill. You can simply use the String.Split method instead:

PS > '47.172.99.12'.Split('.', 2)[1]
172.99.12
PS >

Upvotes: 3

briantist
briantist

Reputation: 47772

You can use the -replace operator instead of split:

'47.172.99.12' -replace '^\d+\.',""

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107287

If you just want the 3 last numbers you can use the following regex :

(\.\d+){3}$

Demo

But if you want every things after the first dot you can use a positive look-behind :

(?<=\.).*

Demo

Upvotes: 2

Related Questions