Author Posts

August 10, 2017 at 12:57 pm

Hi,

I want to deny a variable that has two, or more, dots on a string.

This are allowed values:

40.1 , 45.26, 220.243

This shouldnt' be allowed:

40.1. , 45..26, .220.243, 192.168.44.2

I hate myself for not knowing regex...

August 10, 2017 at 1:20 pm

Certainly not the best way, but I did it using this:

if ($IP.Split(".").Count -gt 2){"Error"}

August 10, 2017 at 1:31 pm

I'm not a Regex guy either, but here's my best effort:

[PS] C:\temp>$a = "40.1"
[PS] C:\temp>$a -match ("^[\d]{1,3}\.[\d]{1,3}$")
True
[PS] C:\temp>$a = "45.26"
[PS] C:\temp>$a -match ("^[\d]{1,3}\.[\d]{1,3}$")
True
[PS] C:\temp>$a = "40.1."
[PS] C:\temp>$a -match ("^[\d]{1,3}\.[\d]{1,3}$")
False
[PS] C:\temp>$a = "45..26"
[PS] C:\temp>$a -match ("^[\d]{1,3}\.[\d]{1,3}$")
False
[PS] C:\temp>$a = ".220.243"
[PS] C:\temp>$a -match ("^[\d]{1,3}\.[\d]{1,3}$")
False
[PS] C:\temp>$a = "192.168.44.2"
[PS] C:\temp>$a -match ("^[\d]{1,3}\.[\d]{1,3}$")
False

Keep in mind that this regex doesn't limit your decimal values to between 0-255, which you may or may not want.

August 10, 2017 at 2:31 pm

This seems to work:

$thing -notmatch ".*\..*\..*"

Admittedly I tried solving it myself and ended up googling it.

I learnt regex a while back but have forgotten most of it. I recall these were very good resources:

-regex buddy (free trials available)
-Sams Teach Yourself Regular Expressions in 10 Minutes

August 10, 2017 at 2:46 pm

The SAMS book is what I use. Highly recommended. No, you wont teach yourself regex in 10 minutes, but it's about as painless an introduction to the subject as I've found. A mastery of Regex is one those skills that separates the men from the boys, IMHO (I count myself as still very much among the boys).

August 10, 2017 at 4:52 pm

David Flores,

Thanks! I managed the 0-255 in another way. =]

August 10, 2017 at 7:14 pm

Here's the solution I came up with using ValidateScript. Note that ValidateScript is not explicitly for parameter validation and can be used anywhere in your scripts if you wish to validate assignment of values to variables etc.

[validatescript({[regex]::matches($_,"\.").count -le 1})]$var = "4.1"

Above works but below doesn't:

[validatescript({[regex]::matches($_,"\.").count -le 1})]$var = "192.168.."