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
#>