1

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

4 Answers 4

3

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 >
Sign up to request clarification or add additional context in comments.

2 Comments

The -split operator allows restricting the number of resulting elements too. You could do $head, $tail = '47.172.99.12' -split '\.', 2 (or $null, $tail = ... if you're not interested in the first octet).
@AnsgarWiechers - True. But I meant more that Regex is inherently less efficient than the Split method (albeit not by much in such a simple case). I don't like to use Regex solutions unless I need to match a variable pattern. For static text though, I prefer the built-in string methods.
2

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

Comments

2

You can use the -replace operator instead of split:

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

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.