0

I want to have a variable that is manage by regex, I want a Permanent code that begin with 4 letters follow by 4 numbers: for the Regex I found this : \D{4}\d{4} it is right, and i don't know how to have a variable that only content 4 letters and 4 numbers.

$permanentCode ="LETT7654"
if($permanentCode=\D{4}\d{4}){

  "valid code"
}

else {
 "invalid code"
}

1 Answers1

1

Firstly, the syntax is wrong. The strings after the assignment operator must be quoted 'LETT7654', and '\D{4}\d{4})'.

RegEx is for matching not assignment. Yet, you could grab stuff with RegEx and assign those results to a variable.

You are also using an assignment operator = vs a comparison -eq in the if statement. The regex needs work of course, because that \d, would match any 4 consecutive digits in the string, the same applies to \D.

Clear-Host
$TestCode = {
    if($PermanentCode -match '(\D{4}\d{4})')
    {'valid code'}
    else {'invalid code'}
}

$PermanentCode = 'LETT7654'
& $TestCode

$PermanentCode = 'LE7654'
& $TestCode

$PermanentCode = 'LETTZ7654'
& $TestCode

$PermanentCode = 'LETT654'
& $TestCode

$PermanentCode = 'LETT7654000000000'
& $TestCode
# Results
<#
valid code
invalid code
valid code
invalid code
valid code
#>

If you really mean to limit the $PermanentCode to only 4 chars and 4 digits; so, a total length maximum of 8. then, something like this should do

Clear-Host
$TestCode = {
    if($PermanentCode -match '^[a-zA-Z]{3}\w\d{4}\b')
    {'valid code'}
    else {'invalid code'}
}

$PermanentCode = 'LETT7654'
& $TestCode

$PermanentCode = 'LE7654'
& $TestCode

$PermanentCode = 'LETTZ7654'
& $TestCode

$PermanentCode = 'LETT654'
& $TestCode

$PermanentCode = 'LETT7654000000000'
& $TestCode

$PermanentCode = 'ZZZZ7654'
& $TestCode
# Results
<#
valid code
invalid code
invalid code
invalid code
invalid code
valid code
#>
postanote
  • 15,138
  • 2
  • 14
  • 25