question

lupinlicious avatar image
0 Votes"
lupinlicious asked lupinlicious edited

need help with regular expression

Hello,

I would like to achieve a regular expression that matches the following criteria in a textbox.

  • First character needs to be a letter.

  • Second characters need to be two numbers.

  • Last characters need to be four letters.

For an example like this: A21ABCD, or G16YUZG etc.
Anyone who knows how to achieve this and I'd be very happy to have this solved.

Here is the code I have:

     function Set-OSDComputerName {
         $ErrorProvider.Clear()
         if ($TBComputerName.Text.Length -eq 0) {
             $ErrorProvider.SetError($GBComputerName, "Please enter a computer name")
         }
         else {
             if ($TBComputerName.Text.Length -gt 6) {
                 $ErrorProvider.SetError($GBComputerName, "Computer name cannot be more than 6 characters")
             }
                 else {
             if ($TBComputerName.Text -match "^[-_]|[^a-zA-Z0-9-_]") {
                 $ErrorProvider.SetError($GBComputerName, "Computer name cannot contain special characters")
             }
        
             else {
                 $OSDComputerName = $TBComputerName.Text.Replace("[","").Replace("]","").Replace(":","").Replace(";","").Replace("|","").Replace("=","").Replace("+","").Replace("*","").Replace("?","").Replace("<","").Replace(">","").Replace("/","").Replace("\","").Replace(",","")
                 $TSEnv = New-Object -COMObject Microsoft.SMS.TSEnvironment 
                 $TSEnv.Value("OSDComputerName") = "$($OSDComputerName)"
                 $Form.Close()
               }
            }
         }
     }



Thaaanks!

windows-serverwindows-server-powershellmem-mdt
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

AndreasBaumgarten avatar image
0 Votes"
AndreasBaumgarten answered AndreasBaumgarten commented

Hi @lupinlicious ,

please don't put my script in your script! My script is just for testing your If-conditions and the RegEx!

Modify your script like this (not tested by myself!):


 function Set-OSDComputerName {
     $ErrorProvider.Clear()
     if ($TBComputerName.Text.Length -eq 0) {
         $ErrorProvider.SetError($GBComputerName, "Please enter a computer name")
     }
     else {
         if ($TBComputerName.Text.Length -gt 7) {
             $ErrorProvider.SetError($GBComputerName, "Computer name cannot be more than 7 characters")
         }
             else {
         if ($TBComputerName.Text -notmatch '^[a-zA-Z][0-9]{2,2}[a-zA-Z]{4,4}$') {
             $ErrorProvider.SetError($GBComputerName, "Computer name must be 1 letter + 2 numbers + 4 letters ")
         }
       
         else {
             $OSDComputerName = $TBComputerName.Text.Replace("[","").Replace("]","").Replace(":","").Replace(";","").Replace("|","").Replace("=","").Replace("+","").Replace("*","").Replace("?","").Replace("<","").Replace(">","").Replace("/","").Replace("\","").Replace(",","")
             $TSEnv = New-Object -COMObject Microsoft.SMS.TSEnvironment 
             $TSEnv.Value("OSDComputerName") = "$($OSDComputerName)"
             $Form.Close()
           }
        }
     }
 }

Btw. I have no clue what you are doing in line 16 .... I don't see any reason to do a replacement of special characters as they are not allowed by the RegEx anyway.


(If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

Regards
Andreas Baumgarten

· 5
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Line 16 can be replaced (no pun intended) by this:

 $OSDComputerName = $TBComputerName -replace "[\[\]:;|=+*?<>\/,]+", ''

And you're correct. It's totally unnecessary given the previous code which checks for "special" characters.

Just FYI, your regex works, but it doesn't need the "{min,max}" quantifiers. A simple "{exact}" quantifier would suffice:

 '^[a-zA-Z][0-9]{2}[a-zA-Z]{4}$'
1 Vote 1 ·

Hi @ RichMatheisen-8856 ,

thanks for your help/hint! I was happy to get the Regex done at all :-)

I think the function code is from "somewhere" and just modified. Maybe that's the reason for the "replace line".


Kind regards
Andreas Baumgarten

0 Votes 0 ·

Thank you for this! I tried the code and I can enter GGGG and the script seems to accept it, however in, PowerShell I can see the following errors:

161706-image.png

Seems to be related to this:

          $TSEnv = New-Object -COMObject Microsoft.SMS.TSEnvironment 
          $TSEnv.Value("$OSDComputerName") = "$($OSDComputerName)"

Do you know how to solve it?

Many thanks


0 Votes 0 ·
image.png (58.2 KiB)

Hi @lupinlicious ,

I can't help you with this.
Your function/script is not working here ... throwing errors at the beginning.

For that reason I wrote "my script" for testing the If and RegEx conditions.

I modified the script a few minutes ago ... it must be -notmatch in your function, not -match. Sorry.

(If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

Regards
Andreas Baumgarten

0 Votes 0 ·

Thaaaaaaaaaaaank you -notmatch did the trick
. I'm so happy and thank you for your effort!

0 Votes 0 ·
AndreasBaumgarten avatar image
0 Votes"
AndreasBaumgarten answered lupinlicious published

Hi @lupinlicious ,

maybe this helps:

 $a = "G14YUZG"
 ## Check First char = letter, char 2 and 3 = numbers, last 4 chars = letter / limit to 7 chars 1 letter + 2 numbers +max 4 letters
 if ($a -match '^[a-zA-Z][0-9]{2,2}[a-zA-Z]{4,4}$') {
     Write-Output "Match"

There is one logic issue with your script:
Based on the regex and your example (e.g. G16YUZG) the computer name is 7 characters (1 letter + 2 numbers + 4 letters) but you check for the length of max 6 characters before.
This doesn't fit together ;-)


(If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

Regards
Andreas Baumgarten

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thank you! I have updated the code below, but it still won't let me enter a computer name like: F21ABCD


   function Set-OSDComputerName {
          $ErrorProvider.Clear()
          $TBComputerName = "G14YUZG"
          if ($TBComputerName.Text.Length -eq 0) {
              $ErrorProvider.SetError($GBComputerName, "Please enter a computer name")
          } 
             else {
              if ($TBComputerName -match '^[a-zA-Z][0-9]{2,2}[a-zA-Z]{4,4}$') {
                  $ErrorProvider.SetError($GBComputerName, "Check First char = letter, char 2 and 3 = numbers, last 4 chars = letter / limit to 7 chars 1 letter + 2 numbers +max 4 letters")
              }
                    
              else {
                  $OSDComputerName = $TBComputerName.Text.Replace("[","").Replace("]","").Replace(":","").Replace(";","").Replace("|","").Replace("=","").Replace("+","").Replace("*","").Replace("?","").Replace("<","").Replace(">","").Replace("/","").Replace("\","").Replace(",","")
                  $TSEnv = New-Object -COMObject Microsoft.SMS.TSEnvironment 
                  $TSEnv.Value("OSDComputerName") = "$($OSDComputerName)"
                  $Form.Close()
         }
     }      
  }
0 Votes 0 ·
lupinlicious avatar image
0 Votes"
lupinlicious answered lupinlicious published

Hello,

Thank you for your fast reply, I have updated the code and now I cannot add a computer name.
I cannot enter a computer name like AAAAAA or F16ASDA. What am I doing wrong?

161647-image.png




   function Set-OSDComputerName {
    
    
          $ErrorProvider.Clear()
          $TBComputerName = "A3uPZL"
          if ($TBComputerName.Text.Length -eq 0) {
              $ErrorProvider.SetError($GBComputerName, "Please enter a computer name")
          }
    
          else {
              if ($TBComputerName.Text.Length -gt 6) {
                  $ErrorProvider.SetError($GBComputerName, "Computer name cannot be more than 6 characters")
              }
    
                  else {
              if ($TBComputerName -match '^[a-zA-Z][0-9][a-zA-Z]{4}') {
                  $ErrorProvider.SetError($GBComputerName, "Computer name must start with letter, year, and random letters")
              }
                    
              else {
                  $OSDComputerName = $TBComputerName.Text.Replace("[","").Replace("]","").Replace(":","").Replace(";","").Replace("|","").Replace("=","").Replace("+","").Replace("*","").Replace("?","").Replace("<","").Replace(">","").Replace("/","").Replace("\","").Replace(",","")
                  $TSEnv = New-Object -COMObject Microsoft.SMS.TSEnvironment 
                  $TSEnv.Value("OSDComputerName") = "$($OSDComputerName)"
                  $Form.Close()
                }
             }
          }
      }



image.png (3.7 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

AndreasBaumgarten avatar image
0 Votes"
AndreasBaumgarten answered lupinlicious edited

Hi @lupinlicious ,

AAAAAA is passing the if in line 11 ( if ($TBComputerName.Text.Length -gt 6) ) because the length is not greater than 6
But doesn't fit the regex (1 letter followed by 2 numbers and 4 letters).

F16ASDA doesn't pass the if in line 11 ( if ($TBComputerName.Text.Length -gt 6) ) because the length is greater than 6 (7 characters)
But fit the regex (1 letter followed by 2 numbers and 4 letters).

I wrote already the 2 if conditions doesn't fit together.

You can use this code to play around. Just add another value in line 1 for testing.

 $b = "G16YUZG", "AAAAAA","A3uPZL","G14YUZG","A21ABCD"
 ForEach ($a in $b) {
     $a
     if ($a.Length -gt 6 ) { Write-Output "Computer name cannot be more than 6 characters / Regex will not be checked" } else {
         ## Check First char = letter, char 2 and 3 = numbers, last 4 chars = letters / limit to 7 chars -> 1 letter +2 numbers + 4 letters
         Write-Output "Length is ok - Checking RegEx ......"
         if ($a -match '^[a-zA-Z][0-9]{2,2}[a-zA-Z]{4,4}$') {
             Write-Output "Regex is matching"
         } else { Write-Output "Regex not matching / 1 letter +2 numbers + 4 letters" }
     } 
 }

If you modify the if ($TBComputerName.Text.Length -gt 6) to if ($TBComputerName.Text.Length -gt 7) (in my script: if ($a.Length -gt 6 ) to f ($a.Length -gt 7 )) it should work as expected.


(If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

Regards
Andreas Baumgarten


· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hello,

Now I'm feeling really stupid, what is $b, $TBComputerName, and then what is $a ?
Why do we need to specify the computer name on the first line? $b = "G16YUZG", "AAAAAA","A3uPZL","G14YUZG","A21ABCD"

The code starts as you suggest, have a look on the attached pictures ( I don't have enough with characters to write them in plain text)


I still cannot enter computer name like "A21ABCD"


Thank you @AndreasBaumgarten for your time and effort with me :)

0 Votes 0 ·
RichMatheisen-8856 avatar image
0 Votes"
RichMatheisen-8856 answered

Based on your I still cannot enter computer name like "A21ABCD", try this:

 function Set-OSDComputerName {
     param(
         [String] $TBComputerName
     )
     if ($TBComputerName.Length -eq 0) {
         "Please enter a computer name"  # replace this line with your code
         return
     }
     if ($TBComputerName.Length -gt 7) {
         "$TBComputerName - Computer name cannot be more than 7 characters"  # replace this line with your code
         return
     }
     if ($TBComputerName -notmatch "^[a-zA-Z][0-9]{2}[a-zA-Z]{4}") {
         "$TBComputerName - Computer name does not match the pattern '<letter><digit>digit><letter><letter><letter><letter>"     # replace this line with your code
         return
     }
     # WHY is/was this code necessary?
     # If the $TBComputerName passes the previous tests it connot contain ANY of the characters you're replacing!
     $OSDComputerName = $TBComputerName -replace "[\[\]:;|=+*?<>\/,]+", ''
     "$TBComputerName is okay"   # replace this line with your code
 }
    
 #
 # some test data
 $TBComputerNames =   'A21ABCD', 'G16YUZG',
                      'A_21ABC', 'G16YUZ-',
                      'A{21ACD', 'G6}UZG}',
                      '-A21ACD', '_G6UZG',
                      'A','B1'
 # an example of the function using the 'data above,
 $TBComputerNames | ForEach-Object {
     Set-OSDComputerName $_
 }

I don't know what your "$ErrorProvider" might be, so I removed it from the code above. I did the same with the code following the setting of the $OSDComputerName.

I've also de-nested your "if" statements and inserted "return" to short-circuit the logic.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.