Avatar of razorbackfan
razorbackfan
 asked on

Extracting an IP address from a string

How do I extract the IP address from a string in Excel (see attached file)
SampleData.xlsx
Microsoft ExcelMicrosoft Office

Avatar of undefined
Last Comment
byundt

8/22/2022 - Mon
Noah

Hi there! :)

You forgot to attach the file.
byundt

You may get the first IP address in each cell with:
=LEFT(A2,FIND(",",A2)-1)

Open in new window

ASKER CERTIFIED SOLUTION
byundt

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Noah

Hi there! :)

You may refer to the following example file: SampleData.xlsx

To extract the first part of the string which is the IP address:
=TRIM(LEFT(A2,FIND(",",A2)-1))

Open in new window


To extract the rest of the string which is after the IP address:
=TRIM(RIGHT(A2,LEN(A2)-FIND(",",A2)))

Open in new window


The part of the string which was used to separate these two parts was the first comma. I also put the TRIM function just in case there are any unwanted spaces at the front or the back of the extracted data.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
byundt

If you want to capture ipv6 addresses, then you may change the formula to:
=IFERROR(ExtractIP($A2,COLUMNS($E2:E2),FALSE),"")

Open in new window


And the code (works for either ipv4 or ipv6) would be:
Function ExtractIP(Text As String, Instance As Long, Optional IPv4 As Boolean = True) As String
Static RegEx As Object
Dim oMatch As Object, oMatches As Object
If RegEx Is Nothing Then Set RegEx = CreateObject("VBScript.RegExp")

With RegEx
    .Pattern = IIf(IPv4, "\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", "\b(?:[A-F0-9]{0,4}:){5,7}[A-F0-9]{1,4}\b")
    .Global = True
    .IgnoreCase = True
    On Error Resume Next
    Set oMatches = .Execute(Text)
    ExtractIP = oMatches(Instance - 1)
End With
End Function

Open in new window

ExtractIP.xlsm