Results 1 to 6 of 6

Thread: [RESOLVED] Extract IP Address from a String

Hybrid View

  1. #1

    Thread Starter
    Member
    Join Date
    Sep 2016
    Posts
    43

    Resolved [RESOLVED] Extract IP Address from a String

    Hello
    I want to extract an IP address xxx.xxx.xxx.xxx from a (connection) string like
    tcp:xxx.xxx.xxx.xxx,1433;Database=pubs etc

    I am confused how to use substring like

    Code:
    dim str as string="tcp:xxx.xxx.xxx.xxx,1433;Database=pubs"
    dim IPAdd as string=substring(str,4,15)   'but the IP substring may be less than 15 characters
    and use a regex expression like
    Code:
    Regex("(?<First>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Second>2[0-4]\d|25" + "[0-5]|[01]?\d\d?)\.(?<Third>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?" + "<Fourth>2[0-4]\d|25[0-5]|[01]?\d\d?)", RegexOptions.IgnoreCase Or RegexOptions.CultureInvariant Or RegexOptions.IgnorePatternWhitespace Or RegexOptions.Compiled)
    Make my day
    gbhsk

  2. #2
    Addicted Member Goggy's Avatar
    Join Date
    Oct 2017
    Posts
    196

    Re: Extract IP Address from a String

    you could always use the split function, it splits a string according to a delimiter in your case the ";" for example
    Utterly useless, but always willing to help

    As a finishing touch god created the dutch

  3. #3

    Thread Starter
    Member
    Join Date
    Sep 2016
    Posts
    43

    Re: Extract IP Address from a String

    Well I just tried the following which seems to work
    Code:
     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim str As String = "tcp:192.168.164.142\SQL_Instance,1433;Initial Catalog=pubs;User ID=sa;Password=XXXX"
            Dim i As Integer = str.IndexOf(":")
            MsgBox(str.Substring(i + 1, str.IndexOf("\", i + 1) - i - 1))
     End Sub
    Another problem now is to validate the 192.168.164.142 as an IP address.
    Any ideas?

  4. #4
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: Extract IP Address from a String

    Quote Originally Posted by gbhsk View Post
    Another problem now is to validate the 192.168.164.142 as an IP address.
    Any ideas?
    Read the post made before this one.
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

  5. #5

    Thread Starter
    Member
    Join Date
    Sep 2016
    Posts
    43

    Re: Extract IP Address from a String

    Great response.
    You guys solved my problem!!

  6. #6
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: Extract IP Address from a String

    That regex seems needlessly complex, or at least "it has more features than you probably care about." Every Regex is like a program, so it's possible to make them do "too much" for your use case.

    If all you want to do is get the string representing the IP address you might consider:
    Code:
    Imports System.Text.RegularExpressions
    
    Module Module1
    
        Sub Main()
            Test("tcp:123.123.123.123,1433;Database=pubs etc")
            Test("tcp:1.12.1.12,1433;Database=pubs etc")
            Test("Should not match.")
            Test("12.3")
    
        End Sub
    
        Private Function TryExtractIp(input As String, ByRef output As String) As Boolean
            Dim pattern = "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
            Dim matchInfo = Regex.Match(input, pattern)
            If matchInfo.Success Then
                output = matchInfo.Value
                Return True
            Else
                output = ""
                Return False
            End If
        End Function
    
        Private Sub Test(ByVal input As String)
            Dim output As String
            If TryExtractIp(input, output) Then
                Console.WriteLine("Extracted |{0}|.", output)
            Else
                Console.WriteLine("|{0}| did not match.", input)
            End If
        End Sub
    
    End Module
    This regex matches any group of 1-3 digits separated by three dots. It isn't going to guarantee invalid IP-like strings such as "999.8.777.4" won't match, but I have a feeling you either don't care or aren't going to encounter those scenarios so it seems like a worthy shortcut to take.

    You could "simplify" the regex to:
    Code:
    "(\d{1,3}\.){3}\d{1,3}"
    But I feel like that does more to hide the intent than help.

    If you really want to validate it is a real IP, it's easier to do without Regex than with:
    Code:
    Imports System.Runtime.CompilerServices
    Imports System.Text.RegularExpressions
    
    Module Module1
    
        Sub Main()
            Test("tcp:123.123.123.123,1433;Database=pubs etc")
            Test("tcp:1.12.1.12,1433;Database=pubs etc")
            Test("tcp:0.12.1.12,1433;Database=pubs etc")
            Test("tcp:1.256.1.12,1433;Database=pubs etc")
            Test("Should not match.")
            Test("12.3")
    
        End Sub
    
        Private Function TryExtractIp(input As String, ByRef output As String) As Boolean
            Dim pattern = "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
            Dim matchInfo = Regex.Match(input, pattern)
            If matchInfo.Success Then
                output = matchInfo.Value
                Return True
            Else
                output = ""
                Return False
            End If
        End Function
    
        Private Function ValidateIp(ByVal input As String) As Boolean
            Dim tokens = input.Split(".")
            Try
                Dim tokenValues = From token In tokens
                                  Select Integer.Parse(token)
                Dim firstValue = tokenValues.First()
                Dim firstIsValid = 0 < firstValue AndAlso firstValue <= 255
                Dim othersAreValid = tokenValues.Skip(1).All(Function(t) 0 <= t AndAlso t <= 255)
                Return firstIsValid AndAlso othersAreValid
            Catch ex As Exception
                Return False
            End Try
        End Function
    
        Private Sub Test(ByVal input As String)
            Dim output As String
            If TryExtractIp(input, output) Then
                Console.Write("Extracted |{0}|. ", output)
                If (ValidateIp(output)) Then
                    Console.WriteLine("Valid.")
                Else
                    Console.WriteLine("Invalid.")
                End If
            Else
                Console.WriteLine("|{0}| did not match.", input)
            End If
        End Sub
    
    End Module
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width