Deny user to input string with two dots


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,

I hate myself for not knowing regex…

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

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

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

[PS] C:\temp>$a = “40.1”
[PS] C:\temp>$a -match (“[1]{1,3}.[\d]{1,3}$”)
[PS] C:\temp>$a = “45.26”
[PS] C:\temp>$a -match (“[2]{1,3}.[\d]{1,3}$”)
[PS] C:\temp>$a = “40.1.”
[PS] C:\temp>$a -match (“[3]{1,3}.[\d]{1,3}$”)
[PS] C:\temp>$a = “45…26”
[PS] C:\temp>$a -match (“[4]{1,3}.[\d]{1,3}$”)
[PS] C:\temp>$a = “.220.243”
[PS] C:\temp>$a -match (“[5]{1,3}.[\d]{1,3}$”)
[PS] C:\temp>$a = “”
[PS] C:\temp>$a -match (“[6]{1,3}.[\d]{1,3}$”)

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

  1. \d ↩︎

  2. \d ↩︎

  3. \d ↩︎

  4. \d ↩︎

  5. \d ↩︎

  6. \d ↩︎

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

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).

David Flores,

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

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.."