Author Posts

August 24, 2018 at 2:56 pm

I am working on a GUI wrapper for a small program, and am trying to limit the characters allowed in a couple of input boxes to only numbers and periods (e.g. IP, DNS, etc.). I can get the numbers by simply matching any non-digit character (see below) but this also negates any periods.

    $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 = 16
        $IPInput.add_TextChanged({
            if($IPInput.Text -match '\D') {
                $IPInput.Text = $IPInput.Text -replace '\D'
                    if($IPInput.Text.Length -gt 0) {
                        $IPInput.Focus()
                        $IPInput.SelectionStart = $IPInput.Text.Length
                    }
            }
        })

I am guessing I will need to use a regex of some sort to capture all numeric values and not disallow periods, but to be honest regex still makes my eyes bleed. I tried something like this:

if(!($IPInput.Text -match '[0-9].')) { ...

But it did not work for me. Hoping someone can suggest a simply way to accomplish this.

August 24, 2018 at 6:46 pm

Below is the regex for ip address.

'192.168.1.1' -match "^(\d{1,3}\.){3}\d{1,3}$"

'a.b' -match "^(\d{1,3}\.){3}\d{1,3}$"

August 29, 2018 at 8:00 pm

I ended up going with the below. It is ugly but it works.

if($IPInput.Text -match '[A-Z!@#$%^&*();;_=+?/|\`"`~{[}}-]')