Issues with quotes in strings

Welcome Forums General PowerShell Q&A Issues with quotes in strings

This topic contains 2 replies, has 3 voices, and was last updated by

 
Participant
2 weeks, 5 days ago.

  • Author
    Posts
  • #126759

    Participant
    Points: 26
    Rank: Member

    I am working on a PowerShell GUI. For one of the fields I want to lock it down to only numbers and periods, for IP address input. After several attempts at regex I ended up cobbling this together:

        $IPInput = New-Object System.Windows.Forms.TextBox
            $IPInput.Location = New-Object System.Drawing.Point(445, 60)
            $IPInput.Size = New-Object System.Drawing.Size(170, 20)
            $IPInput.TextAlign = 'Center'
            $IPInput.MaxLength = 15
            $IPInput.add_TextChanged({
                if($IPInput.Text -match '[A-Z!@#$%^&*();;_=+< ,>?/|\`"`~{[}}-]') {
                    $IPInput.Text = $IPInput.Text -replace '[A-Z!@#$%^&*();;_=+< ,>?/|\`"`~{[}}-]'
                        if($IPInput.Text.Length -gt 0) {
                            $IPInput.Focus()
                            $IPInput.SelectionStart = $IPInput.Text.Length
                        }
                }
            })
    

    This works for every character except a single quote ('). I have tried putting a ` before the quote. Changing the enclosing quotes to "" and then adding the single quote character, and about every other permutation I could think of. Can anyone suggest the best method for including the single quote, or an easy way to exclude anything and everything except numbers and periods?

  • #126765

    Participant
    Points: 324
    Helping Hand
    Rank: Contributor

    There should be a ton of examples of a regex for IP addresses, but what you are using is not at first glance, because nothing is ensuring that you are entering a valid octet (e.g.255). Take a look at this post which uses this regex:

    ^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$
    
  • #126782

    Participant
    Points: 885
    Helping Hand
    Rank: Major Contributor

    How about,

    $IPAddress = '192.168.1.1'
    [System.Net.IPAddress]::TryParse($IPAddress,[ref]'1.1.1.1')
    

    You just need to makes sure $IPAddress.Split('\.').count -eq 4

You must be logged in to reply to this topic.