Is it possible to validate pattern before creating RegEx object in PowerShell?
$Pattern = "[A-Z]{1,3" # Pattern is invalid
$Regex = [regex]::new($Pattern) # this throw an exception
Let say that I have XML file with configuration and there are fields with pattern which will be used in the script. If pattern is not correct I’m getting an error which I would like to avoid.
>Solution :
If you want to avoid dealing with the exception (which you could do with try / catch, as Mathias shows in a comment), you can use the -as operator, which attempts conversion to a given RHS type, and quietly returns $null if that fails:
$valid = $null -ne ($regex = $pattern -as [regex])
-
$validthen contains a Boolean ($trueor$false) that indicates whether$patterncontains a valid regex. -
$regexthen either contains a[regex]instance based on the pattern, or$nullif the pattern isn’t valid.- If all you want to do is to validate the pattern itself, remove the
$regex =part
- If all you want to do is to validate the pattern itself, remove the